在Laravel Eloquent中结合了2到多个查询

时间:2016-07-05 10:06:25

标签: laravel laravel-5 eloquent

我有以下表格:

职业< - occupation_user - >用户

职业< - occupation_vacancy - >空缺

我想找到当前用户分享职业的所有职位空缺......

我通过查询occup_user表来检索用户职业,然后在空缺表上使用whereIn和结果数组来实现它。

我有一种唠叨的感觉,可能有更好的方法,但我看不到它?

有人可以提供建议吗?

public function scopeFilteredForUser($query, $user_id, $university_id) {
    $query->with('occupations')->select('id','university_id','title','employer_name','remuneration','city','state','country','commencement_date','num_positions','expire','contract_type','contract_hours')
        ->whereDoesntHave('users', function($q) use($user_id) {
            $q->where('user_id', $user_id);
        })
        ->withOccupationsFilter($user_id);
}
public function scopeWithOccupationsFilter($query, $user_id) {
    $user_occupations = DB::table('occupation_user')
        ->select('occupation_id')
        ->where('user_id', '=', $user_id)
        ->lists('occupation_id');

    if (empty($user_occupations)) {
        return $query;
    }

    return $query->whereIn('id', function ($query) use ($user_occupations)
    {
        $query->select('vacancy_id')
            ->from('occupation_vacancy')
            ->whereIn('occupation_id', $user_occupations);
    });
}

0 个答案:

没有答案