douxiu6835 2019-06-04 07:51
浏览 28

如何在多对多的关系中使用具有条件的地方

I have 3 tables like this : Centres table :

id | name 

Themes table

id | nomtheme

centre_theme table

id | centre_id | theme_id

And my models are :

Centre.php

 public function themes(){
    return $this->belongsToMany('App\Models\Theme');
}

Theme.php

 public function centres(){
    return $this->belongsToMany('App\Models\Centre');
}

I am trying to recover in a request the "centres" associated with a "theme" if user search for that.

My request is actually :

$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();

But my whereHas function actually return a query like that :

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()
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 目详情-五一模拟赛详情页
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line