Laravel:使用where子句计算相关模型的有效方法



我有两个模型UserPosts

    用户
  • : id、名称
  • 文章: id、标题、文章,user_id

我想检查某些user是否具有给定titleposts

$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()方法。所以希望我在这里错过了一些简单的东西,并且想得太多了。

谢谢

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

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

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

最新更新