我已经能够使用以下原始sql获得所需的查询结果:
select `person`.`id`, `full_name`, count(actions.user_id) as total
from `persons`
left join `actions`
on `actions`.`person_id` = `persons`.`id`
and `actions`.`user_id` = $user
where `type` = 'mp'
group by `persons`.`id`
但我还没能让它有说服力地发挥作用.
基于一些类似的答案,我try 了->where()
或leftJoin()
以内的函数,但每个人的count
个动作还没有被$user
过滤.目前的情况是:
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', 'persons.id')
->where('actions.user_id', $user);
})
->groupBy('persons.id')
->where('type', 'foo')
//->where('actions.user_id', '=', $user)
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
我至少朝着正确的方向前进了roughly英里,对吧...?
如果相关的话,Persons.php
模型有两个actions
关系:
public function actions()
{
return $this->hasMany('Action');
}
public function actionsUser($id)
{
return $this->hasMany('Action')->where('user_id', $id);
}