将两个查询合并为一个laravel

2sbarzqh  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(459)

我有两个问题:
查询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();

但这是行不通的。我是新来的,请帮忙。

ryevplcw

ryevplcw1#

试试这个

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

zpjtge22

zpjtge222#

查看您的查询,您没有 ->where('a.head_id', '=', $id) 在查询2中。
删除该条件并添加 head_id 选择,以便您可以在以后手动检查头部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();
c9qzyr3d

c9qzyr3d3#

试试这个:

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

相关问题