tae*_*kni 9 mysql sql laravel eloquent laravel-4
我已经能够使用以下原始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`
Run Code Online (Sandbox Code Playgroud)
但我还没有能够以雄辩的方式开展工作.
基于一些类似的答案,我尝试过内部->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')]);
Run Code Online (Sandbox Code Playgroud)
我至少在标题大致正确的方向,正确的...?
如果相关,则Persons.php模型有两种actions关系:
public function actions()
{
return $this->hasMany('Action');
}
public function actionsUser($id)
{
return $this->hasMany('Action')->where('user_id', $id);
}
Run Code Online (Sandbox Code Playgroud)
tae*_*kni 15
所以,作为参考,我解决了它:
$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')
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
Run Code Online (Sandbox Code Playgroud)
该->where()子句中leftJoin,奇怪的是,需要在讲话标志着变量通过SQL查询传递正确的(同样,"2"似乎并没有工作,而"2"一样).
Car*_*usa 11
我发现这where并不总是适用于该leftJoin条款
如果将来你遇到任何麻烦,我建议你使用它:
$query = Person::leftJoin('actions', function($q) use ($user)
{
$q->on('actions.person_id', '=', 'persons.id')
->on('actions.user_id', '=', "$user");
})
->groupBy('persons.id')
->where('type', 'foo')
->get(['persons.id', 'full_name', DB::raw('count(actions.id) as total')]);
Run Code Online (Sandbox Code Playgroud)
希望它可以帮助某人.