简体   繁体   English

拥有方的一对多单向查找原则

[英]Doctrine one-to-many UNIDIRECTIONAL find on owning side

Problem definition问题定义

So given this part of Doctrine documentation (and many other articles about bidirectional association and persistence problems), I have a one-to-many association that is unidirectional.因此,鉴于 Doctrine 文档的这一部分(以及许多其他关于双向关联和持久性问题的文章),我有一个单向的一对多关联。 It is between a Club and it's Staff members.它介于ClubStaff之间。 From domain logic, the Club should own the Staff .从领域逻辑来看, Club应该拥有Staff For example, if I used document storage, Staff would be a member of Club .例如,如果我使用文档存储, Staff将是Club的成员。 In 99.9% of domain cases, I have a club and want a list of its staffers.在 99.9% 的域案例中,我有一个club并想要一份其员工名单。

However, I am having trouble implementing this idea in Doctrine.但是,我无法在 Doctrine 中实现这个想法。 Because in Doctrine the ONE-TO-MANY relationship has only an inverse side.因为在教义中,一对多关系只有相反的一面。 So even conceptually the following Entity definition is wrong, but I do not know any better.所以即使在概念上,以下实体定义也是错误的,但我不知道更好。

Entity code实体代码

<?php

class Club
{
    /**
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
     */
    public ?UuidInterface $id;

    /**
     * @ORM\Column(type="string", name="name")
     */
    public string $name;

    /**
     * @ORM\OneToMany(targetEntity="Staff", mappedBy="club")
     */
    public Collection $staff;

    public function __construct(string $name)
    {
        $this->id       = Uuid::uuid4();
        $this->name     = $name;
        $this->staff    = new ArrayCollection();
    }

    public function addStaff(Staff $staff): void
    {
        $this->staff->add($staff);
    }

}

class Staff
{
    public const ROLE_OWNER = 'owner';

    /**
     * @ORM\Id
     * @ORM\Column(type="uuid", unique=true)
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
     */
    public ?UuidInterface $id;

    /**
     * @ORM\Column(type="string", name="user_id")
     */
    public string $userId;

    /**
     * @ORM\Column(type="string", name="role")
     */
    public string $role;

    public function __construct(string $userId, string $role)
    {
        $this->id     = Uuid::uuid4();
        $this->userId = $userId;
        $this->role   = $role;
    }
}

But here comes the real problem.但真正的问题来了。 I have ONE use case, where I want to find clubs for the appropriate staffer.我有一个用例,我想为合适的员工找到俱乐部。 It is a (ONE-)MANY-ONE problem, with the caveat that the first one is not another Doctrine entity, but a userId for the Staff entity.这是一个 (ONE-)MANY-ONE 问题,需要注意的是第一个不是另一个 Doctrine 实体,而是Staff实体的userId

So I tried several approaches to getting Club entities given userId :所以我尝试了几种方法来获取给定userId Club实体:

Failed attempts失败的尝试

<?php
   // 1. Naive solution, just try to use the `ObjectRepository`
   // Will cause: You cannot search for the association field 'Club#staff', because it is the inverse side of an association. Find methods only work on owning side associations.
$staffers = $this->em->getRepository(Staff::class)->findBy(['userId' => $ownerId]);
$clubs = $this->em->getRepository(Club::class)->findBy(['staff' => $staffers]);

   // 2. Use `QueryBuilder` naively
   // Will cause: [Semantical Error] line 0, col 131 near 'staff = s.id': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected
         $qb = $this->em->createQueryBuilder();
         $query = $qb->select('c')
         ->from(Club::class, 'c')
         ->join(Staff::class, 's', Join::WITH, 'c.staff = s.id')
         ->where('s.userId = :id')
         ->setParameter('id', $ownerId)
         ->getQuery();

    // 3. Use `QueryBuilder` with knowledge if actual DB columns
    // Will cause: [Semantical Error] line 0, col 138 near 'club_id WHERE': Error: Class Staff has no field or association named club_id
         $qb = $this->em->createQueryBuilder();
         $query = $qb->select('c')
         ->from(Club::class, 'c')
         ->join(Staff::class, 's', Join::WITH, 'c.id = s.club_id')
         ->where('s.userId = :id')
         ->setParameter('id', $ownerId)
         ->getQuery();

    // 4. Create query directly
    // Will cause: [Semantical Error] line 0, col 125 near 'staff = s.id': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected
                $query = $this->em->createQuery('SELECT c FROM ' . Club::class . ' c JOIN ' . Staff::class . ' s WITH c.staff = s.id WHERE s.userId = :id')->setParameter('id', $ownerId);

WHat am I looking for?我在寻找什么?

  • a unidirectional association between Club and Staff , so that I don't have to be careful about persistence, performance, inconsistencies, etc. Just all the problems of bidirectional associations. ClubStaff之间的单向关联,这样我就不必担心持久性、性能、不一致等问题。只是双向关联的所有问题。
  • either:任何一个:
    • a possible rework of the entities/associations实体/协会的可能返工
    • a way to retrieve Club entities, given staff.userId一种检索Club实体的方法,给定staff.userId

A solution that is working, but I am unable to provide an explanation as to why this one works and others do not.一个有效的解决方案,但我无法解释为什么这个解决方案有效而其他解决方案无效。

<?php
$this->em->createQueryBuilder()
            ->select('c')
            ->from(Club::class, 'c')
            ->innerJoin(Staff::class, 's')
            ->where('s.userId = :owner')
            ->setParameter('owner', $ownerId)
            ->getQuery()
            ->getResult();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM