来自 ManyToMany 关联的连接表是否可用于查询?

Are join-tables from a ManyToMany association available for querying?

我正在尝试在我的发票存储库中创建一个查询,查询 return 所有 没有任何 Payment[=28] 的发票 =]与它相关联。

这两个实体之间存在多对多关联(注意 invoice_payment 联接 table),如下面的实体定义摘录所示:

Class 发票:

/**
 * @ORM\ManyToMany(targetEntity="Payment", inversedBy="invoice_ids")
 * @ORM\JoinTable(   name="invoice_payment",
 *            joinColumns={@ORM\JoinColumn(name="invoice_ids", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="payment_ids", referencedColumnName="id")} )
 */
protected $payment_ids;

Class 付款:

    /**
     * @ORM\ManyToMany(targetEntity="Invoice", mappedBy="payment_ids")
     */
    protected $invoice_ids;

我知道如果我可以访问连接 table invoice_payment 它应该是一个非常简单的查找 - 但是我没有在 Symfony/Doctrine 中找到任何讨论访问的内容非实体数据库 tables。这可能吗?

据我所知,用 Doctrine 是不可能的,但你可以做的是使用普通的 mysql 来访问所需的 table.

类似于:

$this->getDoctrine()->somefunctiontogetpuremysql()->query(SELECT * FROM "invoice_payment")

抱歉,我不记得那个函数是什么,你得自己去找。这种方法使用起来有点烦人,因为你没有得到实体,你得到的是简单的数据。

您也可以在两个 table 上将 ManyToMany 分成 ManyToOne 和 OneToMany,然后将其变成一个实际的实体。

试试这个。

$qb = $this->createQueryBuilder('i');
$qb->leftJoin('i.payments_ids', 'p')
   ->andWhere('p is null');

在旁注中,您的字段名称具有误导性。 payments_ids 应称为付款 - invoice_ids 与 inoices 相同。 他们 return 没有 id,他们 return 对象的集合。