[英]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. 我想检索数据,即使id_user还没有,因为我必须显示类型和汽车。 I added the leftJoin constraint with a
where "null" or where cars_user.userid = ?
我在
where "null" or where cars_user.userid = ?
添加了leftJoin约束, 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. 但是如果用户3选择了用户1尚未选择的一种汽车(因为它不会为null或userid = 1),它将不再显示汽车。
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 如果用户13没有为该类型指定任何汽车,如果我没有此行,它将不会显示,因为用户14选择了一辆
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. 需要
DB::raw
以避免Eloquent引用原始值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.