Ad

Laravel 5 Search Related Models

- 1 answer

I have two related model.

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

And

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

How I can find girl model by related target id?

  $girls = Girl::where('banned', 0)
             ->with('target');

 $targets=$seachSettings->target()->get();
            if($targets!=null){
                foreach ($targets as $item) {
                    //     $girls->target()->array_where();
                    $girls->target()->where('girl_target','target_id',$item->id);
                }
            }

I want get only models where related targets with id from my $targets array.

Ad

Answer

You need to use whereHas() method

$girls = Girl::whereHas('target', function ($query) use($item) {
    $query->where('id', $item->id);
})->where('banned', 0)->with('target');
Ad
source: stackoverflow.com
Ad