2017-11-25 186 views
1

我想在這裏查詢Laravel Eloquent。如何讓Laravel雄辯(hasMany)和WhereIn查詢?

有兩個模型文件和標籤。 文件有標籤的關係 - 有許多

class File extends Model 
    .... 
    public function tags() 
    { 
     return $this->hasMany('App\Models\Tags'); 
    } 
..... 
} 

每個文件有很多標籤,並在需要具有所有標籤的文件。

例如:

文件1具有標籤1,2,3

文件2具有標籤2,3

當我搜索標籤2,獲取文件2,當我搜索標籤1和2我希望只有文件1有兩個標籤。

的funktions我試圖

$files = File::with(['tags' => function ($query){ 
     $query->whereIn('tag_id', array(1,2)); 
    }])->get(); 

$files = File::whereHas('tags', function ($query) { 
      $query->whereIn('tag_id', [1,2]); 
     })->get(); 

,但我得到的文件1 UND 2,我只需要文件1 TAG 1und2

+0

那麼你應該獨立,並使用2個whereHas通過簡單的邏輯每個標籤的ID。 –

回答

1

像更改如下─

代碼
$tag_ids=[1,2]; 
$files = File::whereHas('tags', function ($query) use ($tag_ids){ 
     foreach($tag_ids as $tag_id){ 
     $query->where('tag_id', '=',$tag_id); 
     } 
    })->with('tags')->get(); 

這將像查詢您的tag_ids

0

我已經找到了解決

$q = File::with('tags'); 
    foreach ($tag_ids as $tag_id) { 
     $q->whereHas('tags', function ($query) use ($tag_id){ 
      $query->where('tag_id', '=', $tag_id); 
     }); 
    } 
    $files = $q->get();