Las*_*ode 2 php symfony doctrine-orm
我在我的存储库类上有一个方法来获取Article它们的联接(类别,图像...),但并不是每个人Article都有类别或图像,这不能使我得到所有预期的结果,导致我当前的存储库功能仅返回Article具有Categories而Image不是null,而忽略具有null值的内容。
我的Article实体有以下关系。
/**
* @ORM\ManyToMany(targetEntity="App\ArticleBundle\Entity\Category", cascade={"persist"})
*/
private $categories;
/**
* @ORM\ManyToOne(targetEntity="App\ArticleBundle\Entity\Image", cascade={"persist"})
*
*/
private $image;
Run Code Online (Sandbox Code Playgroud)
这是我的存储库功能
public function getArticle($id)
{
$qb = $this->createQueryBuilder('a')
->where('a.id = :theId')
->setParameter('theId', $id)
->join('a.author', 'auth')
->addSelect('auth')
->join('a.categories', 'cat')
->addSelect('cat')
->join('a.image', 'img')
->addSelect('img');
return $qb->getQuery()->getOneOrNullResult();
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道如果我能得到Article具有categories,image或不符合参加一个查询。我想说的是,在使用Doctrine延迟加载时(通过避免查询中的联接),我得到了预期的结果。
使用->leftJoin()让Article具有categories,image或者没有在一个查询:
public function getArticle($id)
{
$qb = $this
->createQueryBuilder('a')
->addSelect('auth', 'cat', 'img')
->join('a.author', 'auth')
->leftJoin('a.categories', 'cat')
->leftJoin('a.image', 'img')
->where('a.id = :theId')
->setParameter('theId', $id)
;
return $qb->getQuery()->getOneOrNullResult();
}
Run Code Online (Sandbox Code Playgroud)
因此,当Doctrine尝试以惰性方式加载相关属性时,可以避免额外的查询。
说明:
使用->join()或->innerJoin():
这是最简单,最容易理解的Join,也是最常见的。该查询将返回左表(表A)中所有与右表(表B)中具有匹配记录的记录。
使用->leftJoin():
该查询将返回左表(表A)中的所有记录,无论这些记录中的任何一条在右表(表B)中是否匹配。它还将从右表中返回所有匹配的记录。
来源:CL Moffatt详细解释了SQL联接的可视表示
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |