表user
示例:
id | name | status | first_name | last_name | create_at
表post
示例:
id | title | name | description | user_id | status | create_at
在model user
中:
public function posts()
{
return $this->hasMany(Post::class);
}
在model post
中:
public function users()
{
return $this->belongsTo(Users::class);
}
post table 数据库中有一个status
列,有1、2、3三个值,现在我想统计有多少个status=1,有多少个status = 2, 3
< /p>
我有两种处理方式,就是使用关系或者调用post模型来处理
在UserController.php
:
// The best way to try is relationship
$user = User::select(['id', 'name'])
->with(['posts:user_id'])
->where('type', 2)
->get();
或者:
$user = User::select(['id', 'name'])
->where('type', 2)
->get();
foreach ($user as $val) {
$statusPublic[] = Posts::where('user_id', $val['id'])->where('status', '=', 1)->count();
$statusPrivate[] = Posts::where('user_id', $val['id'])->whereIn('status', [2, 3])->count();
}
我的问题是在帖子表中有 300,000 个项目。如果你这样处理状态计数,它会很慢。有时长达20s。有什么办法可以改善吗?谢谢
答案 0 :(得分:1)
您需要使用 withCount。
在模型用户
public function posts_status_one()
{
return $this->hasMany(Post::class)->where('status', '=', 1);
}
public function posts_status_other()
{
return $this->hasMany(Post::class)->whereIn('status', [2, 3]);
}
现在在您的查询中
$user = User::select(['id', 'name'])
->withCount(['posts_status_one', 'posts_status_other'])
->where('type', 2)
->get();
通过使用 withCount n + 1 查询,将减少到 3 查询。
答案 1 :(得分:0)
您应该使用 whereHas()
方法
User::where('type', 2)->whereHas('posts', function($q) {
$q->where('status', '=', 1);
})->count();