简体   繁体   中英

Combine two query as single laravel

I have two queries:

Query 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();

Query 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();

both single query working well.. I am trying to combine there two queries as single query so I've tried

$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();

But this is not working. I am new in laravel, please help.

try this:

$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();

try this one

$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();

using where group you can create and or query group for better result group wise

Looking at your queries, you don't have ->where('a.head_id', '=', $id) in Query 2.

Remove that condition and add the head_id to the select so that you can manually check if the head_id matches afterwards:

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM