mysql join ON and AND to laravel eloquent

北城以北 提交于 2020-01-01 02:43:48

问题


I've been able to get the query result I need using the following raw 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`

But I haven't been able to get it working in eloquent yet.

Based on some similar answers, I'd tried functions within ->where() or leftJoin(), but the count of each person's actions isn't yet being filtered by $user. As it stands:

$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')]);

I'm at least heading in roughly the right direction, right...?

If it's relevant, the Persons.php model has two actions relationships:

public function actions()
{
    return $this->hasMany('Action');
}

public function actionsUser($id)
{
    return $this->hasMany('Action')->where('user_id', $id);
}

回答1:


So, for reference, I solved it like so:

$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')]);

The ->where() clause within leftJoin, oddly, needs the speech marks for the variable to be passed through the sql query correctly (likewise, '2' doesn't seem to work while "2" does).




回答2:


I found that the where doesn't always work on the leftJoin clause

If in the future you get any trouble with it, I'd suggest you using this:

    $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')]);

Hope it helps someone.



来源:https://stackoverflow.com/questions/27460945/mysql-join-on-and-and-to-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!