簡體   English   中英

Laravel 5.6通過活動記錄進行選擇

[英]Laravel 5.6 selection by active records

用戶表

depart_id | user_role

5 | 1個

4,2 | 2

5,2 | 2

1,5 | 1個

我想使用user_role = 1和depart_id = 5和depart_id = 1獲取所有用戶

如何實現使用活動記錄(或常規查詢)?

我的代碼是

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

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

您創建了錯誤的數據庫結構。 最佳方法-創建表users_departs(user_id,depart_id)

然后您可以這樣做:

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

我認為沒有一個簡單的whereIn可以在這里工作。 給定表的架構,在列(IMO)中分配多個鍵不是一個好習慣
但您可以嘗試一下。 我嘗試使用LIKE語句。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM