2016-12-01 49 views
3

我有文章,並在每個文件的相應的功能標籤型號:Laravel交叉路口數據

Article.php:

public function tags() 
    { 
     return $this->belongsToMany('App\Tag')->withTimestamps(); 
    } 

Tag.php:

public function articles() 
    { 
     return $this->belongsToMany('App\Article'); 
    } 

在刀片觀點,我可以通過致電

@foreach($tag->articles as $article) 
    ... 
@endforeach 

從上面,我可以訪問一個標籤的文章數量。我們如何過濾具有多個標籤的商品,僅說明在標籤模型中同時具有tag1tag2的商品?

回答

2

這是做的native way你想要什麼:

$tags = ['tag1', 'tag2']; 
$articles = Article::whereHas('tags', function ($query) use ($tags) { 
    $query->whereIn('tag', $tags); 
})->get(); 

如果你願意,你可以使用動態查詢範圍,使其稍微更具可讀性:

// Article.php 

public function scopeTagged($query, $tags) 
{ 
    $query->whereHas('tags', function ($q) use ($tags) { 
     $q->whereIn('tag', (array)$tags); 
    }); 
} 

這樣,你可以這樣做這在查詢物品時:

Article::tagged('tag1')->get(); 
Article::tagged(['tag1', 'tag2'])->get();