【问题标题】:Laravel: efficient way to count related models with where clauseLaravel:使用 where 子句计算相关模型的有效方法
【发布时间】:2017-02-18 07:29:32
【问题描述】:

我有两个型号UserPosts

  • 用户:id、姓名
  • 帖子:id、标题、帖子、user_id

我想检查一些user 是否有posts 和给定的title

$user = User::find($userId);
$posts = $user->posts;
$postsWithGivenTitle = $posts->where('title','=',$title);
$postCount = $postsWithGivenTitle->count();

我认为上面的方法应该可行,但我需要超越它并有效地做到这一点。所以我得到了这个并且它正在工作,但仍然不确定它是否是正确的方法。

$user = User::find($userId)->withCount(['posts' => function ($q) use ($title) {
    $q->where('title','=',$title);
}])->first();

然后检查计数:

if ($user->posts_count > 0) { 
    //do something
}

让我感到困惑并且看起来很丑的是在同一个查询中使用方法find()first()。所以希望我在这里遗漏了一些简单的东西并且想多了。

谢谢

【问题讨论】:

    标签: php mysql eloquent laravel-5.2 relationship


    【解决方案1】:

    您可以在文档中看到:https://laravel.com/docs/5.3/eloquent-relationships

    你可以这样实现你想要的:

    $user = User::withCount(['posts' => function($q){....}])->find($id)
    

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 2014-10-15
      • 2015-05-11
      • 1970-01-01
      • 2017-02-17
      • 2019-01-23
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多