- Added partial support for Index as primary keys

This commit is contained in:
Dave Mc Nicoll 2025-03-11 19:36:00 +00:00
parent e0ec140661
commit bfddf84564
4 changed files with 24 additions and 9 deletions

View File

@ -5,6 +5,7 @@ namespace Ulmus\Common;
use Notes\Common\ReflectedClass; use Notes\Common\ReflectedClass;
use Notes\Common\ReflectedProperty; use Notes\Common\ReflectedProperty;
use Psr\SimpleCache\CacheInterface; use Psr\SimpleCache\CacheInterface;
use Ulmus\Attribute\Obj\Index;
use Ulmus\Ulmus, use Ulmus\Ulmus,
Ulmus\Attribute\Obj\Table, Ulmus\Attribute\Obj\Table,
Ulmus\Attribute\Obj\AdapterAttributeInterface, Ulmus\Attribute\Obj\AdapterAttributeInterface,
@ -214,9 +215,9 @@ class EntityResolver {
return null; return null;
} }
public function getCompoundKeyFields() : ? array public function getCompoundKeyFields() : ? Index
{ {
return null; return $this->getAttributeImplementing(Index::class);
} }
public function getUniqueFields() : ? array public function getUniqueFields() : ? array

View File

@ -144,13 +144,27 @@ trait EntityTrait {
return false; return false;
} }
if ( null === $pkField = $this->resolveEntity()->getPrimaryKeyField($this) ) { if ( null === $pkField = $this->resolveEntity()->getPrimaryKeyField() ) {
throw new Exception\EntityPrimaryKeyUnknown(sprintf("Entity %s has no field containing attributes 'primary_key'", static::class)); if ( null !== $compoundKeyFields = $this->resolveEntity()->getCompoundKeyFields() ) {
$loaded = false;
foreach ($compoundKeyFields->column as $column) {
$field = $this->resolveEntity()->field($column);
if (! $field->allowsNull() ) {
$loaded |= isset($this->{$field->name});
}
}
return $loaded;
};
}
else {
$key = key($pkField);
return isset($this->$key);
} }
$key = key($pkField); throw new Exception\EntityPrimaryKeyUnknown(sprintf("Entity %s has no field containing attributes 'primary_key'", static::class));
return isset($this->$key);
} }
#[Ignore] #[Ignore]

View File

@ -97,7 +97,7 @@ class Repository implements RepositoryInterface
else { else {
$pk = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField(); $pk = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();
if (count($pk) === 1) { if ($pk && count($pk) === 1) {
$field = key($pk); $field = key($pk);
$this->select(Common\Sql::function('COUNT', Common\Sql::raw("DISTINCT " . $this->entityClass::field($field)))); $this->select(Common\Sql::function('COUNT', Common\Sql::raw("DISTINCT " . $this->entityClass::field($field))));