Laravel 5.6按活动记录选择

User table

depart_id         | user_role

5                       | 1

4,2                    | 2

5,2                    | 2

1,5                    | 1

I want to fetch all user with user_role=1 and depart_id=5 and depart_id=1

How to achieve using active record(or usual query)?

My code is

$user_depart = array(5,1);
$user_role   = 1;

$data = DB::table('tbl_users')
            ->where('user_role', $user_role)
            ->whereIn('department_id',$user_depart)
            ->get();

You have created an bad database structure. Best way - create table users_departs (user_id, depart_id)

And then you can do like this:

$userDeparts = [5,1];
$userRole = 1;
$users = User::with('users.departs')
    ->where('users.role_id', $userRole)
    ->whereIn('departs.id', $userDeparts)
    ->get();

I dont think a simple whereIn will work here. Given the schema of your table it is not quite a good practice assigning multiple keys in your column (IMO)
but you could give a try this. I tried using LIKE statement.

$user_depart = array(5,1);
$user_role   = 1;

$data = DB::table('tbl_users')
        ->where('user_role', $user_role)
        ->where(function($sql) use ($user_depart){
             for($i = 0; $i < count($user_depart); $i++){
                  $sql->orWhere('department_id','LIKE','%' . $user_depart[$i] . '%');
             }
        })
        ->get();