Laravel 5通过多对多关系选择项目

时间:2019-04-05 21:16:04

标签: laravel-5 select many-to-many

我有很多对很多的关系。

 class Girl extends Model
{
 public function target()
  {
    return $this->belongsToMany('App\Target','girl_target');
  }
 }

class Target extends Model{   
 public function girl()
{
    return $this->belongsToMany('App\Girl', 'girl_target');
}

}


     $girls = Girl::query();

    $girls
        ->where('sex', $with_met)
        ->where('meet', $who_met)
        ->where('age', '>=', $request->min_age)
        ->where('age', '<=', $request->max_age);

    if ($request->get('targets')) {
        //$book->whereHas('categories', function($query) use($request) {
                $girls->whereHas('target', function ($query) use ($request) {
            $query->whereIn('id', $request->get('targets'));
        });
    }
    $girls=$girls->get();

并返回错误:

  

SQLSTATE [23000]:违反完整性约束:1052子句>含糊不清的列“ id”(SQL:从girls中选择*,其中sex = famele和> meet =男性且age> = 18和age <= 40并存在(从target上的> girl_target内部联接target中选择*。id => girl_targettarget_id,其中girlsid = girl_targetgirl_id和(1)中的> id))

如何使用关系正确选择?

0 个答案:

没有答案