比方说,您有一个搜索结果页面,该页面可以按多种标准显示汽车,包括发布年份。
当用户未指定年份时,我想从每个品牌的最新可用年份中撤出所有汽车(“ year_models”)。例如,您会看到2019年的雪佛兰,但会看到2009年的庞蒂亚克。在每个品牌表中,我都有一个“ latest_year”列可用于此目的。
关系:
每个品牌都有许多brand_models。每个品牌模型都有很多year_models。
如何执行此查询?到目前为止,这是我的代码:
$year = $request['year'];
$yearModels = YearModel::with([
'brandModel',
'brandModel.brand',
])
->when(!$year, function ($q) {
$q->whereHas('brandModel.brand', function ($q) use ($year) {
$q->where('latest_year', $YEARMODEL_YEAR?? );
});
})
...
我也尝试了“ wherecolumn”查询,但我认为我无法以这种方式查询品牌关系。
答案 0 :(得分:0)
我认为您正在考虑做类似的事情
$query = YearModel::with([
'brandModel',
'brandModel.brand',
]
);
if (!$year) {
$query = $query->whereRaw('column_one', 'column_2');
}
$result = $query->get();
此thread可能会对您有所帮助。您可能需要根据表结构更改查询。
修补匠的例子
>>> App\models\Student::whereRaw('standard_id', 'section_id')->get()
=> Illuminate\Database\Eloquent\Collection {#3225
all: [
App\models\Student {#3226
id: 1,
first_name: "Farhan",
last_name: "Pasha",
gender: "m",
date_of_birth: "2001-02-02",
roll_number: 1,
standard_id: 1,
section_id: 1,
school_id: 1,
photo: "",
created_at: "2019-10-07 07:36:21",
updated_at: "2019-10-10 10:42:37",
},
App\models\Student {#3213
id: 2,
first_name: "Mohameed",
last_name: "Khalil",
gender: "m",
date_of_birth: "2013-05-27",
roll_number: 2,
standard_id: 1,
section_id: 1,
user_id: 1,
school_id: 1,
photo: "",
created_at: "2019-10-14 07:15:10",
updated_at: "2019-10-14 07:15:10",
},
],
}
>>>
答案 1 :(得分:0)
考虑如何使用普通SQL编写此查询,可能应该是这样的:
SELECT b.brand, bm.model, ym.year from brands b
left join brand_models bm on b.id = bm.brand_id
left join year_models ym on ym.model_id = bm.model_id
group by b.brand, bm.model, ym.year having ym.year = max(ym.year)
然后尝试将其转换为雄辩的语言。
$brands = Brands::with(["brandModel", "brandModel.yearModel")
->groupBy("id, brandModel.id, brandModel.yearModel.id");
if(!isset($year)){
$brands = $brands->having("brand.yearModel.year", "=", \DB::raw("max(brandModel.yearModel.year)"));
} else {
$brands = $brands->having("brand.yearModel.year", "=", $year);
}
$results = $brands->get();