How can I prevent loading of related entities in Symfony2?

余生长醉 提交于 2020-01-16 04:46:05

问题


I have two entities, Order and Orderline with one-to-many relationship. I have a listing where I need only data from orders, but Doctrine makes query for orderlines for each order. I haven't joined Orderlines in the query. How can prevent Doctrine for querying the orderlines?

Query used in controller:

$query = $em->createQuery("SELECT o FROM SomeBundle:Order o JOIN o.shop s JOIN s.user u WHERE u.id = :user_id AND o.status = :status")
    ->setParameter('user_id', $user->getId())
    ->setParameter('status', 'paid');
$orders = $query->getResult();

One-to-many annotation in Order class:

/**
 * @ORM\OneToMany(targetEntity="Orderline", mappedBy="order")
 */
protected $orderlines;

Many-to-one annotation in Orderline class:

/**
 * @ORM\ManyToOne(targetEntity="Order", inversedBy="orderlines")
 */
protected $order;

回答1:


Give a hint to doctrine using Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD

$query = $em->createQuery("SELECT partial o.{id} FROM SomeBundle:Order o JOIN o.shop s JOIN s.user u WHERE u.id = :user_id AND o.status = :status")
    ->setParameter('user_id', $user->getId())
    ->setParameter('status', 'paid');

$query->setHint(Doctrine\ORM\Query::HINT_FORCE_PARTIAL_LOAD, 1);

$orders = $query->getResult();

OR

See this http://docs.doctrine-project.org/en/2.1/tutorials/extra-lazy-associations.html



来源:https://stackoverflow.com/questions/15729224/how-can-i-prevent-loading-of-related-entities-in-symfony2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!