简体   繁体   中英

How to add a condition in Eloquent query based on related model data?

If you have a query that uses eager loading like this:

Brand::with('tags')
  ->where('id', $id)
  ->get();

A brand can have many tags .

I then also have an array of tag ids like this [2,4] . How do I add a condition to this query where it returns only those brands whose tags are in the array?

I tried the eager load constraints but that condition is then placed on the tags model, not the Brand .

I tried this also but it returns an unknown method error:

public function tagsIn($allTags){
    return $this->belongsToMany('App\Tag', 'brand_tags')
        ->whereIn('tags.id', $allTags);
}

Brand::with('tags')
  ->tagsIn('[2,4]')
  ->get();

I suspect a possible limitation to getting it to work is the fact that Eloquent makes two separate database calls. But is there a way nevertheless?

试试这个DB::table('name')->whereIn('column', array(1, 2, 3))->get();

I think you should use this package to handle tag. I used it in my projects. laravel-tagging

DB::table('Brands')
    ->join('brand_tag','brands.id','=','brand_tag.brand_id')
    ->join('tags','brand_tag.tag_id','=','tags.id')
    ->whereIn('tags.id',$allTags)
    ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM