将两个查询组合为单个laravel

问题描述 投票:0回答:3

我有两个问题:

查询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的新人,请帮忙。

mysql laravel
3个回答
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
投票

试试这个

$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查询组以获得更好的结果组明智


1
投票

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

删除该条件并将head_id添加到select中,以便您可以手动检查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();
© www.soinside.com 2019 - 2024. All rights reserved.