【问题标题】:Laravel 5 - ORM has() Relationship (Inverse - notHas)Laravel 5 - ORM has() 关系(逆 - notHas)
【发布时间】:2016-02-29 00:05:48
【问题描述】:

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

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

由于没有像notHas 这样的方法,我怎样才能找到所有没有 cmets 的帖子? (记住这是hasMany 关系)


参考:

查询关系存在

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

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      旧主题,但为像我这样来自 Google 的人提供了更新的答案。现在你可以只使用 doesntHave()。

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

      参考:

      查询关系缺失

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

      【讨论】:

      • Dominik Lenz 你让我的生活变得轻松,谢谢,这应该是最好的答案
      猜你喜欢
      • 2015-04-16
      • 2016-08-27
      • 2017-10-21
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2014-06-22
      相关资源
      最近更新 更多