如果存在关系,请获取OneToMany“Child”以返回“Parent”对象

时间:2015-01-27 16:10:51

标签: php symfony doctrine-orm silex doctrine-query

使用下面的doctrine docs示例,我希望能够在查询产品时返回所有功能。

如此有效selecting all products where feature.product_id = product.id

但是如果可能的话,我想这样做以学说面向对象的方式。在学说中是否有任何方式以相反的方式匹配这些关系?

<?php
use Doctrine\Common\Collections\ArrayCollection;

/** @Entity **/
class Product
{
    // ...
    /**
     * @OneToMany(targetEntity="Feature", mappedBy="product")
     **/
    private $features;
    // ...

    public function __construct() {
        $this->features = new ArrayCollection();
    }
}

/** @Entity **/
class Feature
{
    // ...
    /**
     * @ManyToOne(targetEntity="Product", inversedBy="features")
     * @JoinColumn(name="product_id", referencedColumnName="id")
     **/
    private $product;
    // ...
}

来源:http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#one-to-many-bidirectional

谢谢,

1 个答案:

答案 0 :(得分:0)

在这种情况下选择产品,其中product.id = feature.product_id只返回1个结果,假设您的产品表的ID是其主键,自动递增。您确定自己并未尝试返回所有功能,其中feature.product_id ==(特定产品.id)?

如果是后者,

$features = $em->getRepository('MyBundle:Feature')
    ->findBy(
        array('product_id' => $productId)
    );

你手边有$ productId,一个唯一的整数。