简体   繁体   中英

SQL Force Left Join to Print No Match

I have a problem with a query. I have a bunch of cars, and there are types of cars. For each type, a user can select one car, and I'm saving this in the database. When I want to retrieve the data I run into trouble:

[
  {
    "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",
      }
]

And my query :

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

I wanted to retrieve the data even if the id_user is not there yet because I must display types and cars. I added the leftJoin constraint with a where "null" or where cars_user.userid = ? but if user 3 chose one type of car that user 1 has not chosen (because it won't null or userid = 1), it would not display cars anymore.

Thank you!

EDIT :

Actual output :

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

Expected output :

+---------------------------------+
| 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                 |
+---------------------------------+

If I don't have this line if the user 13 didn't specify any cars for this type it won't display since user 14 has chosen one

Based on deleted answer, I solved my issue :

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 is needed to avoid Eloquent from quoting raw values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM