【问题标题】:Doctrine2: How to select ArrayCollection using DQLDoctrine2:如何使用 DQL 选择 ArrayCollection
【发布时间】:2016-07-12 05:24:29
【问题描述】:

我有两个实体,它们的 OneToMany 映射方式与学说文档中描述的方式完全相同:

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

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

当我在Product 上执行findAll() 时,它会返回带有Feature 数组的产品。

我正在使用DQL 进行查询,所以我想知道如何使用DQL 选择Feature 的数组。

我做到了:SELECT p.name, p.price, f FROM Product p JOIN p.features f

但它给出了一个错误

如果不选择至少一个根实体别名,则无法通过标识变量选择实体。

我也试过了:SELECT p.name, p.price, p.features FROM Product p

这也会报错

无效的路径表达式。必须是 StateFieldPathExpression。

【问题讨论】:

  • 你能把你的 PHP 代码也去掉吗? DQL 本身看起来并没有错,但问题在于您如何称呼它。

标签: php mysql symfony doctrine-orm doctrine


【解决方案1】:

问题在于,如果没有获取 Product 来包含它,您就无法获取 Features 实体。所以你必须这样做

SELECT p , f FROM Product p JOIN p.features f

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    @abdiel 给出了正确的解决方案

    class ProductsRepository extends \Doctrine\ORM\EntityRepository
    {
    
        public function getAllProductsWithFeatures()
        {
            $dql = 'SELECT p , f FROM Product p JOIN p.features f';
            $query = $this->getEntityManager()->createQuery($dql);
            return $query->getResult();
        }
    
    }
    

    然后例如在控制器中:

    $products = $this->get('doctrine')->getRepository('YourBundle:Product')->getAllProductsWithFeatures();
    

    所有产品都将带有预加载的功能集合。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多