【问题标题】:Get OneToMany 'Child' to return object of 'Parent' if relationship is present如果存在关系,则获取 OneToMany 'Child' 以返回 'Parent' 的对象
【发布时间】:2015-01-27 16:10:50
【问题描述】:

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

如此有效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

谢谢,

【问题讨论】:

  • 如果我错了,请纠正我,但这大致就是您要做的事情:仅检索那些 具有 已分配功能的产品,但跳过那些 没有分配功能的产品 功能。我说的对吗?
  • 正是@JovanPerovic 抱歉延迟回复

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


【解决方案1】:

在这种情况下选择一个产品,其中 product.id = feature.product_id 只会返回 1 个结果,假设您的产品表的 id 是它的主键,自动递增。您确定您没有尝试返回所有 features 其中 feature.product_id == (specific product.id) 的地方吗?

如果是后者,

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

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

【讨论】:

  • 嗨,不,我想要所有与特定产品相关联的功能,例如“尺寸”的功能
  • 我的答案中的代码应该返回链接到特定产品的所有功能,其中您有产品实体,因此有产品 ID。如果这不是您想要的,您可以考虑修改您的问题。
  • 取消 Jovan 的评论,“仅检索那些已分配功能的产品,但跳过那些没有功能的产品”
猜你喜欢
  • 2022-09-25
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多