表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
我有两种处理方式,就是使用关系或者调用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。有什么办法可以改善吗?谢谢