如何根据相关模型数据在Eloquent查询中添加条件?

时间:2016-09-01 10:11:47

标签: php mysql laravel eloquent

如果您的查询使用了这样的预先加载:

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

brand可以包含多个tags

然后我还有一个像[2,4]这样的标记ID数组。如何在此查询中添加一个条件,它只返回标签位于数组中的品牌?

我尝试了急切的加载限制,但是这个条件会放在tags模型上,而不是Brand

我也试过这个,但它返回unknown method错误:

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

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

我怀疑使其工作的可能限制是Eloquent进行两次单独的数据库调用。但是还有办法吗?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我认为你应该使用这个包来处理标签。我在我的项目中使用它。 laravel-tagging

答案 2 :(得分:0)

Directory.CreateDirectory(outputDir); //App is trying to create directory
//successfully created but depends on OS how fast OS commits the changes

Thread.Sleep(500); //assuming physically creation on Hard and its availability in OS took less then 500ms then this wait works or else we have to wait more

//this delay is actually totally non generic since the time differs OS to OS


 // its just a rough guess that changes will be committed within 500ms

if(!Directory.Exists(outputDir))
  //if still not exists Your OS que is being processed very slow due to 
  //some not known reason! so you have to wait more then 500ms