How can I prevent loading of related entities in S

2019-07-27 12:17发布

问题:

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