【问题标题】:Doctrine: QueryBuilder Where Exists学说:QueryBuilder 存在的地方
【发布时间】:2013-09-05 15:32:44
【问题描述】:

回答

我能够在 where 子句中使用 IS NOT EMPTY 进行查询。

/**
 * Finds all developments having at least one image.
 *
 * @param string
 * @return array
 */
public function withImages()
{
    return $this->query->createQueryBuilder('d')
        ->where('d.images IS NOT EMPTY')
        ->getQuery()
        ->getResult();
}

问题

我正在使用 Doctrine ORM。我希望能够获得至少具有一个图像的所有开发,这样对于查询中选择的每个开发,以下属性都是正确的。 $development->getImages()->count()) > 0.

我有一个 Development 实体,它与 Image 实体具有一对多关系。

/**
 * The Development class provides an abstraction of a development. 
 *
 * @Entity
 * @HasLifecycleCallbacks
 * @Table(name="developments")
 **/
class Development extends BaseEntitiy {

    /** @OneToMany(targetEntity="Exquisite\Entity\Image", mappedBy="development") **/
    protected $images;

我有一个 DevelopmentRepository,它有一个 EntityManager 的实例和一个实体的 Repository 实例。我已尝试在 DevelopmentRepository 类的 withImages() 方法中执行此操作,但运气不佳。

class DevelopmentRepository implements DevelopmentRepositoryInterface {


    /**
     * Class Constructor
     *
     * @param Doctinre\ORM\EntityManager  The EntityManager instance.
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
        $this->query = $this->em->getRepository('Exquisite\Entity\Development');
    }


    /**
     * Finds all developments having at least one image.
     *
     * @param string
     * @return array
     */
    public function withImages()
    {
            $qb = $this->query->createQueryBuilder('d');
            $qb2 = $this->em->createQueryBuilder();

            return $qb->where($qb->expr()->exists($qb2->select('i.development')->from('Exquisite\Entity\Image', 'i')->getDql()))
                ->getQuery()
                ->getResult();
    }

任何帮助将不胜感激!

【问题讨论】:

    标签: php doctrine-orm relationship exists


    【解决方案1】:

    我遇到了同样的问题,这对我有用。

    我修复了只做一个连接(只会返回带有项目的订单):

    return $this->createQueryBuilder('so')
            ->select('so')
            ->join('so.orderItems', 'soi')
            ->getQuery()
            ->getResult();
    

    或者用 DQL 做一个子查询

    SELECT so
    FROM Entity\\SalesOrder so
    WHERE (SELECT count(soi.id) FROM Entity\\SalesOrderItem soi WHERE soi.salesOrder = so.id ) > 0
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2016-08-25
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多