如何使用Doctrine查询无关联评论的Book表数据?
用Doctrine实现查询无关联评论的书籍
方法一:对应原生NOT IN子查询的实现
如果要和你给出的原生SQL逻辑完全匹配,可以通过Doctrine的子查询来实现。假设你的实体类为App\Entity\Book和App\Entity\Comment,且Comment实体中存在指向Book的ManyToOne关联字段(比如$book)。
QueryBuilder写法
在BookRepository中添加查询方法:
public function findBooksWithoutComments() { // 构建子查询:获取所有存在评论的书籍实例 $subQuery = $this->getEntityManager()->createQueryBuilder() ->select('c.book') ->from(App\Entity\Comment::class, 'c'); // 主查询:筛选不在子查询结果中的书籍 return $this->createQueryBuilder('b') ->where('b NOT IN (:commentedBooks)') ->setParameter('commentedBooks', $subQuery->getDQL()) ->getQuery() ->getResult(); }
直接DQL写法
也可以直接编写DQL语句完成查询:
public function findBooksWithoutComments() { $dql = 'SELECT b FROM App\Entity\Book b WHERE b NOT IN (SELECT c.book FROM App\Entity\Comment c)'; return $this->getEntityManager()->createQuery($dql)->getResult(); }
方法二:LEFT JOIN + IS NULL(更稳妥的方案)
当comments表中存在book_id为NULL的记录时,原生NOT IN可能出现不符合预期的结果(NULL会导致NOT IN条件不成立)。这种情况下,使用LEFT JOIN结合IS NULL的方式更可靠:
QueryBuilder写法
public function findBooksWithoutComments() { return $this->createQueryBuilder('b') ->leftJoin('b.comments', 'c') // 需确保Book实体定义了OneToMany的comments关联 ->where('c.id IS NULL') ->getQuery() ->getResult(); }
注:需要在Book实体中提前定义关联关系:
// App\Entity\Book 类中 /** * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="book") */ private $comments;
内容的提问来源于stack exchange,提问作者user2626210
相关产品推荐
相关产品推荐

