Laravel 5 - ORM有()关系(Inverse - notHas)

时间:2015-11-26 01:53:22

标签: php laravel laravel-5

在Laravel 5中,我可以使用has方法查找至少有一条评论的所有帖子:

// Retrieve all posts that have at least one comment...
$posts = App\Post::has('comments')->get();

由于没有类似notHas的方法,如何找到所有没有评论的帖子? (记住它是hasMany关系)

参考:

查询关系存在

http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

2 个答案:

答案 0 :(得分:5)

据我所知,还没有notHas()方法,但查找关系数小于1的记录通常会满足此要求:

$posts = App\Post::has('comments', '<', 1)->get();

答案 1 :(得分:0)

旧话题,但对于像我这样来自Google的人来说,答案已更新。如今,您可以只使用nottHave()。

$posts = App\Post::doesntHave('comments')->get();

参考:

查询关系缺失

https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-absence