Laravel查询具有可选条件的多对多表

时间:2016-10-10 14:12:56

标签: laravel eloquent

我有3张表格如下

经销商

 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 个答案:

答案 0 :(得分: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();