在laravel利用聯合查詢時兩個數據表按照某一字段排序

在laravel利用聯合查詢時兩個數據表按照某一字段排序

在項目中需要把兩個表的數據按照時間進行排序,需要利用mysql的兩個查詢

代碼:

$tourist = Tourist::query()
            ->select('id', 'name as customer_name', 'created_at as time', DB::raw("2 as type, 0 as status"))
            ->when(!empty($search), function ($query) use ($search) {
                $like = '%' . $search . '%';
                $query->where('name', 'like binary', $like)
                    ->orWhere('mobile', 'like binary', $like);
            })->when(empty($search), function ($query) {
                $query->whereBetween('created_at', TimeHelper::today());
            });
 $builder = Customer::query()
     ->select('id', 'customer_name', 'register_time as time', DB::raw("1 as type, status"))
     ->where('delete_time', 0);

 if ($search) {
     $like = '%' . $search . '%';
     $builder->where(function ($query) use ($like) {
         $query->where('customer_name', 'like binary', $like)
             ->orWhere('mobile', 'like binary', $like)
             ->orWhere('email', 'like binary', $like);
     });
 } else {
     $builder->whereBetween('register_time', TimeHelper::today());
 }

 $userList = $builder->union($tourist)
     ->orderByDesc('time')
     ->offset(($page - 1) * $per_page)
     ->limit($per_page)
     ->get()->toArray();

程序解釋:

  1. DB::raw("2 as type, 0 as status") 意思是:給tourist表 和customer 表添加一個虛擬的數據type(tourist爲2, customer爲1)表明如果id有重複可以知道這個id對應的那個表的數據記錄:
    效果:
 // 說明 type=2 是tourist中的記錄, type=1是customer中的記錄
{
     "id": 55,
     "customer_name": "13246532066",
     "time": 1552127193,
     "type": 1,
     "status": 1
 }, {
     "id": 16,
     "customer_name": "HGH",
     "time": 1552095123,
     "type": 2,
     "status": 0,
 },
  1. 在我的使用mysql 中的like 模糊查詢是,不區分大小寫問題
    深入瞭解:
    在MySQL中,對於Column Collate其約定的命名方法如下:
    *_bin: 表示的是binary case sensitive collation,也就是說是區分大小寫的
    *_cs: case sensitive collation,區分大小寫
    *_ci: case insensitive collation,不區分大小寫

    解決辦法:

    • 修改需要進行模糊查詢字段的 Collate
    • 在進行模糊查詢的時候,在like的後面加個binary就可以了,適用於表的結構不易改變的情況下(以上例子用此辦法)
  2. 若需要按照某一字段進行排序,需要確保排序的字段的名字相同的,如上例中的time 如果兩個數據表中的字段不一樣可以使用as設置別名的辦法

  3. 若要使用條件查詢,需要在各自的sql builder中填寫對應的條件查詢語句

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章