2016-10-10 144 views
0

我有3个表如下Laravel查询到多对多表可选条件

经销商

id - dealer_name 

特色

id - name 

dealer_specialty

id - dealer_id - specialty_id 

所以经销商和专业模型有多对多的关系,船舶所以在他们的模型,他们看起来像

Dealer.php

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

在Speciality.php

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

现在我有一种情况,其中用户可以过滤结果。首先将显示整个经销商表格。现在用户可以过滤结果与专业和经销商的名称。所以我已经制定了可选参数的路线。而在我的控制器上,我正在检查参数是否不变空置条件。它只与dealer_name一起工作,其条件是指它自己的表。当我需要把特殊表放在哪里时,我遇到了问题。

我的代码看起来像

$dealerArray = DB::table('dealers'); 
if(!empty($speciality)) { 
    // how to put where condition like get all dealers with specialit id 4, if this condition matches. I have tried following but its definitely generating error. 
    $dealerArray->specialities()->where('blah blah blah'); 
    //I have also tried whereHas.. 
} 
if(!empty($keyword)) { 
    $dealerArray->where('dealer_name','Like','%'.$keyword.'%'); 
} 

return $dealerArray->get() ; 

所以最后我想知道我怎么可以把一个选择条件。如果我有过滤从专业ID经销商,我怎么能做到这一点。

回答

1

试试这个 在Dealer.php

public function specialties() 
{ 
    return $this->belongsToMany(Speciality::class, 'dealer_specialty', 'dealer_id', 'specialty_id'); 
} 

在Speciality.php

public function dealers() 
{ 
    return $this->belongsToMany(Dealer::class, 'dealer_specialty', 'specialty_id', 'dealer_id'); 
} 

查询

$dealerArray = new Dealer(); 

    if (!empty($speciality)) { 
     // how to put where condition like get all dealers with speciality id 4, 
     // if this condition matches. I have tried following but its definitely generating error. 

     $dealerArray = $dealerArray->whereHas('specialties', function ($query) use ($speciality) { 
      $query->where('specialty_id', $speciality); 
     }); 

     //I have also tried whereHas.. 
    } 

    if (!empty($keyword)) { 
     $dealerArray = $dealerArray->where('dealer_name', 'Like', '%' . $keyword . '%'); 
    } 
    return $dealerArray->get(); 
+0

谢谢你的男孩。这是我正在寻找的 –