У меня есть 3 таблицы, как это:
Таблица центров:
id | name
Таблица тем
id | nomtheme
centre_theme table
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()