将两个查询合并为单个Laravel

时间:2018-09-05 05:53:21

标签: mysql laravel

我有两个查询:

查询1

$usersdetails = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname', 'b.mode as mode')
    ->where('a.head_id', '=', $id)
    ->where('b.mode', '=', 'proceed')
    ->get()->toArray();

查询2

$usersdetailsApp = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname', 'b.mode as mode')
    ->where('b.mode', '=', 'Approved')
    ->get()->toArray();

两个查询都运行良好。 我试图将两个查询合并为一个查询,所以我尝试了

$usersdetails = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname', 'b.mode as mode')
    ->where('a.head_id', '=', $id)
    ->where('b.mode', '=', 'proceed')
    ->orWhere('b.mode', '=', 'Approved')
    ->get()->toArray();

但这不起作用。我是laravel的新手,请帮助。

3 个答案:

答案 0 :(得分:2)

尝试一下:

$usersdetails = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname', 'b.mode as mode')
    ->where(function ($query) use ($id) {
        $query->where('a.head_id', $id)->orWhereIn('b.mode',
            ['proceed', 'Approved']);
    })
    ->get()->toArray();

答案 1 :(得分:1)

尝试这个

$usersdetails = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname','b.mode as mode')
    ->where('a.head_id', '=', $id)
    ->where(function($query){
         $query->where('b.mode', '=', 'proceed');
         $query->orwhere('b.mode', '=', 'Approved');
     })
    ->get()->toArray();

使用where group,您可以创建and or查询组,以更好地实现明智的结果组

答案 2 :(得分:1)

在查看查询时,查询2中没有->where('a.head_id', '=', $id)

删除该条件并将head_id添加到选择项中,以便之后可以手动检查head_id是否匹配:

$usersdetails = DB::table('users as a')
    ->join('Appraiser_commands as b', 'a.id', '=', 'b.user_id')
    ->select('a.id as userid', 'b.cycle_id as cycleid', 'a.name as uname', 'b.mode as mode', 'a.head_id as headid')
    ->where('b.mode', 'proceed')
    ->orWhere('b.mode', 'Approved')
    ->get()->toArray();