简体   繁体   English

如何在主义中加入多对多关系?

[英]How to join many-to-many relations in Doctrine?

I've got some entities: 我有一些实体:

Supplier: 供应商:

/**
 * @ORM\Entity(repositoryClass="Blah\Blah\ApiClientBundle\Entity\SupplierRepository")
 */
class Supplier
{
    [...]

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Blah\SopBundle\Entity\SupplierUser", mappedBy="suppliers")
     */
    protected $users;

    [...]
}

SupplierUser: SupplierUser:

/**
 * @ORM\Entity(repositoryClass="SupplierUserRepository")
 */
class SupplierUser
{
    [...]

        /**
         * @var ArrayCollection
         *
         * @ORM\ManyToMany(targetEntity="\Blah\Blah\ApiClientBundle\Entity\Supplier", inversedBy="users", cascade={"persist"})
         * @ORM\JoinTable(name="supplier_user_supplier",
         *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="user_id", onDelete="CASCADE")},
         *      inverseJoinColumns={@ORM\JoinColumn(name="supplier_id", referencedColumnName="supplier_id")}
         * )
         * @Assert\Valid()
         */
        protected $suppliers;

    [...]
}

Now in one repository I join the entities mentioned above to one report (rpr): 现在,在一个存储库中,我将上述实体与一个报告(rpr)结合在一起:

public function findBrandsBySupplierUser(SupplierUser $supplierUser)
{
    return array_column(
        $this
            ->createQueryBuilder('rpr')
            ->join(Supplier::class, 's', 'WITH', 's.supplierId = rpr.supplierId')
            ->join(SupplierUser::class, 'su')
            ->where('su = :supplierUser')
            ->setParameters([
                'supplierUser' => $supplierUser,
            ])
            ->select('rpr.brand')
            ->distinct()
            ->orderBy('rpr.brand')
            ->getQuery()
            ->getArrayResult(),
        'brand'
    );
}

But the result is: 但是结果是:

SELECT DISTINCT r0_.brand AS brand_0 FROM returnable_products_report r0_ 
INNER JOIN supplier s1_ ON (s1_.supplier_id = r0_.supplier_id)
INNER JOIN supplier_user s2_
WHERE s2_.user_id = ?
ORDER BY r0_.brand ASC

So I receive a Cartesian join. 所以我得到了笛卡尔的加入。 Why doesn't Doctrine join automatically? 为什么教义不能自动加入?

I could opt for enforcing the the join fields, but I don't know how exactly to do it. 我可以选择强制加入连接字段,但是我不知道该怎么做。 How should join(SupplierUser::class, 'su') look in such case? 在这种情况下join(SupplierUser::class, 'su')应该如何看待?

The working answer seems to be: 可行的答案似乎是:

->join('s.users', 'su')

instead of 代替

->join(SupplierUser::class, 'su')

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

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