Skip to content

Relations and entity collections

To-one relations

The key map is written as local field => target field.

use Small\SwooleEntityManager\Entity\Attribute\ToOne;

#[ToOne(UserManager::class, ['userId' => 'id'])]
private ?UserEntity $user = null;

Load it lazily:

$project->loadToOne('user');
$user = $project->getUser();

Create an empty related entity through relation metadata:

$newUser = $project->newToOne('user');

To-many relations

use Small\SwooleEntityManager\Entity\Attribute\ToMany;
use Small\SwooleEntityManager\Entity\EntityCollection;

#[ToMany(ProjectManager::class, ['id' => 'userId'])]
private ?EntityCollection $projects = null;
$user->loadToMany('projects');
$projects = $user->getProjects();
$newProject = $user->newToMany('projects');

Eager relation loading

findBy() and findOneBy() accept dependency paths. Each path is represented as an alias chain.

$users = $userManager->findBy(
    ['enabled' => true],
    [
        ['projects'],
    ],
);

Nested paths can specify the source alias explicitly:

$users = $userManager->findBy(
    [],
    [
        ['projects'],
        ['projects' => 'owner'],
    ],
);

Composite relation keys

Relations may map several key pairs. The generated SQL joins every pair with AND.

#[ToOne(
    ProductManager::class,
    [
        'productId' => 'id',
        'buildStrate' => 'buildStrate',
    ],
)]
private ?ProductEntity $product = null;

This is required for stratified relation graphs so rows from different snapshots are never mixed.

Custom entity collections

use Small\SwooleEntityManager\Entity\Attribute\Collection;

#[Collection(UserEntityCollection::class)]
#[OrmEntity]
final class UserEntity extends AbstractEntity
{
}

The collection class must extend EntityCollection. Collections validate that every item is an AbstractEntity and provide:

  • persist();
  • delete();
  • toArray();
  • reformatKeys();
  • setAllFromDb();
  • setAllOriginalPrimaryKeys().

persist() and delete() use a persistence thread when the selected driver supports one.

Next chapter: Select query builder