使用现有模型进行Laravel查询

时间:2018-10-11 13:47:42

标签: laravel eloquent

我有两个模型:“优惠”和“专业”,具有很多对很多的关系:

在Offer.php

public function specialities()
{
    return $this->belongsToMany('App\Speciality');
}

in Speciality.php

public function offers()
{
    return $this->belongsToMany(Offer::class);
}

到目前为止,这很简单。

现在,我正在构建查询以仅获取具有特定特殊性的优惠。问题是我正在使用when辅助函数,所以我不知道如何访问专业模型:

public function template($person = "", $speciality = "")
{
      $offers = Offer::when($speciality, function($query, $speciality) {
        return $query->specialities()->where('speciality_name', $speciality)->get();
      })->orderBy('created_at','desc')->paginate(9);
}

这对我不起作用。谁能给我一个小费,我应该怎么写?

2 个答案:

答案 0 :(得分:3)

使用whereHas()

$offers = Offer::when($speciality, function($query, $speciality) {
    $query->whereHas('specialities', function($query) use($speciality) {
        $query->where('speciality_name', $speciality);
    });
})->orderBy('created_at', 'desc')->paginate(9);

答案 1 :(得分:2)

对于查询,您应该使用join而不是specialities()关系, 因此它将更像:

 $offers = Offer:join('offer_specialities os', 'offer.id', 'os.offer_id')
 ->join('specialities', 'specialities.id', 'os.speciality_id')
 ->when($speciality, function($query, $speciality) {
    return $query->where('specialities.speciality_name', $speciality)->get();
  })->orderBy('created_at','desc')->paginate(9);