我有3张这样的桌子: 中心表:
id | name
主题表
id | nomtheme
centre_theme表
id | centre_id | theme_id
我的模型是:
Centre.php
public function themes(){
return $this->belongsToMany('App\Models\Theme');
}
Theme.php
public function centres(){
return $this->belongsToMany('App\Models\Centre');
}
如果用户进行搜索,我试图在请求中恢复与“主题”相关的“中心”。
我的请求实际上是:
$theme_id = $request->input('theme');
$centres = Centre::where('statut', 'Publié')->with('region', 'dept',
'photocentre', 'themes')
->wherehas('themes', function($centres) {
if(isset($theme_id) && !empty ($theme_id)) {
$centres->where('theme_id', '=', 1);
}
})
->where(function($centres) use ($id_localisationdept) {
if(! empty($id_localisationdept)) {
$centres->where('dept_id', $id_localisationdept->id);
}})
->where(function($centres) use ($id_localisationregion) {
if(! empty($id_localisationregion)) {
$centres->where('region_id', $id_localisationregion->id);
}})
->when(isset($dept_id) || isset($region_id), function ($q) {
return $q->orderByRaw("CASE WHEN plan = 'Basic' THEN 3 WHEN plan = 'Pro' THEN 2 WHEN plan = 'Premium' THEN 1 ELSE 4 END");
},
function ($q) {
return $q->orderByRaw("CASE WHEN plan = 'Premium' THEN 1 ELSE 4 END");
}
)
->inRandomOrder()
->get();
但是我的whereHas函数实际上返回了这样的查询:
select * from `centres` where `statut` = 'Publié' and exists (select * from `themes` inner join `centre_theme` on `themes`.`id` = `centre_theme`.`theme_id` where `centres`.`id` = `centre_theme`.`centre_id`) and (`capacite` > 80 and `capacite` <= 120) order by CASE WHEN plan = 'Premium' THEN 1 ELSE 4 END, RAND()