簡體   English   中英

SQL強制左聯接以打印不匹配

[英]SQL Force Left Join to Print No Match

我有一個查詢問題。 我有一堆汽車,而且有多種汽車。 對於每種類型,用戶可以選擇一輛汽車,而我將其保存在數據庫中。 當我想檢索數據時遇到麻煩:

[
  {
    "id_typecar": 1,
    "nom_typecar": "Type17",
    "id_car": 14,
    "id_user": 3,
    "cars": [
      {
        "id_car": 1,
        "nom_car": "775",
        }
      },
      {
        "id_car": 2,
        "nom_car": "048",
      }
    ]
  },
  {
 //Not displayed if user_id != 1 or null -> I want to display that
    "id_typecar": 2,
    "nom_typecar": "Type1",
    "id_car": 13,
    "id_user": 1, //expected output "id_user": null
    "cars": [
      {
        "id_car": 11,
        "nom_car": "123",
      },
      {
        "id_car": 12,
        "nom_car": "456,
      },
      {
        "id_car": 17,
        "nom_car": "789",
      }
]

和我的查詢:

    return TypeCars::with('cars')
        ->leftJoin('cars_user', 'cars_user.id', '=', 'type_cars.id')
        ->where('cars_user.id' = 1)
        ->orWhereNull('cars_user.id')
        ->get()
        ->toJson();

我想檢索數據,即使id_user還沒有,因為我必須顯示類型和汽車。 我在where "null" or where cars_user.userid = ?添加了leftJoin約束, where "null" or where cars_user.userid = ? 但是如果用戶3選擇了用戶1尚未選擇的一種汽車(因為它不會為null或userid = 1),它將不再顯示汽車。

謝謝!

編輯:

實際輸出:

+---------------------------------+
| id_typecar name_typecar id_user |
+---------------------------------+
| 1 Type1Car 14                   |
| 2 Type2Car 13                   |
| 2 Type2Car 13                   |
| 3 Type3Car NULL                 |
+---------------------------------+

預期產量:

+---------------------------------+
| id_typecar name_typecar id_user |
+---------------------------------+
| 1 Type1Car 14                   |
| 1 Type1Car NULL                 | <-- needed for the display
| 2 Type2Car 13                   |
| 2 Type2Car 14                   |
| 3 Type3Car NULL                 |
| 3 Type3Car NULL                 |
+---------------------------------+

如果用戶13沒有為該類型指定任何汽車,如果我沒有此行,它將不會顯示,因為用戶14選擇了一輛

基於刪除的答案,我解決了我的問題:

return TypeCars::with('cars')->leftJoin('user_cars', function($join){
    $join->on('user_cars.id', '=', 'type_cars.id');
        $join->on('user_cars.id', '=', DB::raw(1)); 
})
    ->whereNull('user_cars.id')
    ->where('user_cars.id', '=', 1)
    ->get()
    ->toJson();

需要DB::raw以避免Eloquent引用原始值。

暫無
暫無

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

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