我有一个与实体所有者有多对一关系的Car实体.如果我选择所有汽车,Doctrine会在Car表上执行一个查询,然后在每个汽车的Owner表上进行一次查询.因此,获取N个汽车变为N 1个查询,而不是Car和Owner表之间的单个JOIN查询.
我的实体如下:
/** @Entity */ class Car { /** @Id @Column(type="smallint") */ private $id; /** @ManyToOne(targetEntity="Owner",fetch="EAGER") @JoinColumn(name="owner",referencedColumnName="id") */ private $owner; public function getId() { return $this->id; } public function getOwner() { return $this->owner; } } /** @Entity */ class Owner { /** @Id @Column(type="smallint") */ private $id; /** @Column(type="string") */ private $name; public function getName() { return $this->name; } }
如果我想与他们的车主列出汽车,我会这样做:
$repo = $em->getRepository('Car'); $cars = $repo->findAll(); foreach($cars as $car) echo 'Car no. ' . $car->getId() . ' owned by ' . $car->getOwner()->getName() . '\n';
现在这一切都很有效,除了Doctrine为每辆车发出查询这一事实.
SELECT * FROM Car; SELECT * FROM Owner WHERE id = 1; SELECT * FROM Owner WHERE id = 2; SELECT * FROM Owner WHERE id = 3; ....
当然我希望我的查询日志看起来像这样:
SELECT * FROM Car JOIN Owner ON Car.owner = Owner.id;
我是否有fetch =“EAGER”或fetch =“LAZY”并不重要,即使我在两个实体之间使用JOIN进行自定义DQL查询,$car-> getOwner()仍会导致Doctrine查询数据库(除非我使用EAGER,在这种情况下,$repo-> findAll()会导致所有这些).