php - Doctrine 在 JOIN 选择上返回空对象

标签 php mysql symfony doctrine-orm doctrine

我的 symfony 类存储库中有这个函数:

public function findAllByIdShop($id)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT s, c
            FROM  AppBundle:ShopCategory s
            JOIN  s.category c
            WHERE s.shop = :shop_id
            ORDER BY c.name'
        )
        ->setParameter(':shop_id', $id)
        ->getResult();
}

查询返回最后一个记录类别(别名 c)作为 NULL 值,如果我通过“SELECT s”更改选择行,我将通过延迟加载 Doctrine 获得正确的结果,我想避免延迟加载。

例如,如果我在存储库查询中有四个名为“c1、c2、c3、c4”的类别,我将获得 null 的 c4。

我的类看起来像那样(请注意,我使用多对一、单向关系来避免双向关系)

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShopCategory
 *
 * @ORM\Table()
 * @ORM\Entity
  */
class ShopCategory
{


    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Shop")
     */
    private $Shop;


    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Category")
     */

    private $Category;


    /**
     * Set Shop
     *
     * @param AppBundle\Entity\Shop $Shop
     * @return ShopCategory
     */
    public function setShop(\AppBundle\Entity\Shop $Shop)
    {
    $this->Shop = $Shop;

    return $this;
    }

    /**
     * Get Shop
     *
     * @return AppBundle\Entity\Shop
     */
    public function getShop()
    {
    return $this->Shop;
    }

    /**
     * Set Category
     *
     * @param AppBundle\Entity\Category $Category
     * @return ShopCategory
     */
    public function setCategory(\AppBundle\Entity\Category $Category)
    {
    $this->Category = $Category;

    return $this;
    }

    /**
     * Get Category
     *
     * @return AppBundle\Entity\Category 
     */
    public function getCategory()
    {
    return $this->Category;
    }
}

最佳答案

试试这个

 public function findAllByIdShop($id)
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT s, c
                FROM  AppBundle:ShopCategory sc
                JOIN  sc.category c
                JOIN  sc.shop s
                WHERE s.<id_field> = :shop_id
                ORDER BY c.name'
            )
            ->setParameter(':shop_id', $id)
            ->getResult();
    }

关于php - Doctrine 在 JOIN 选择上返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128425/

相关文章:

php - 更新和插入 mysqli 表

php - 如何禁用 SELECT QUERY 对结果进行自动排序

mysql - 有什么方法可以在没有子查询的情况下加入这两个查询?

php - Sylius:添加具有可翻译内容的资源

php - Symfony2 插入错误参数[null,null,null]

php - 尽管对文件进行了更改,但 filemtime() 在执行期间保持不变

javascript - 输入正确值后重新加载网页

php - 根据相同或不同的值检查并更新行

mysql - java.sql.SQLNonTransientConnectionException : Public Key Retrieval is not allowed in jhipster docker production for monolithic project

php - 有没有办法禁用 symfony2/doctrine 约束?