【发布时间】:2015-02-12 04:27:07
【问题描述】:
我已经能够使用以下原始 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`
但我还不能让它在 eloquent 中工作。
基于一些类似的答案,我尝试了->where() 或leftJoin() 中的函数,但是$user 尚未过滤每个人的操作的count。就目前而言:
$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')]);
我至少在大致朝着正确的方向前进,对吧...?
如果相关,Persons.php 模型有两个 actions 关系:
public function actions()
{
return $this->hasMany('Action');
}
public function actionsUser($id)
{
return $this->hasMany('Action')->where('user_id', $id);
}
【问题讨论】:
-
您是否在
Person.php类中指定表名是persons?如果不是,Laravel 将尝试调用 Person 的复数形式,在本例中为 People 表。 -
啊,对不起 - 我用这里的名字来掩盖实际正在做的事情,我没有意识到 Laravel 这么聪明!
标签: mysql sql laravel laravel-4 eloquent