我被困在這裏一直試圖從2-3小時。laravel 5.1獲取相關5多對多關係的每個類別的新聞
我有一個多對多的關係:
class Category extends Model
{
public function news()
{
return $this->belongsToMany('App\News');
}
}
class News extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
我想獲得最新的5日消息相關類別:
$front_categories = Category::with(array(
'news'=>function($query){
$query->where('publish','1')->orderBy('created_at', 'desc')->take(5);}))
->where('in_front', 1)->get();
上面的查詢不工作對我來說它給一個每個類別共有5個結果,而不是5個結果。
我所做的是 $ front_categories =類別::這裏('in_front ',1) - > orderBy('position','asc') - > get(); 在我的分類模型 public function newsTop5() { return $ this-> news() - > orderBy('created_at','desc') - > take(5); } 和我的刀片 @foreach($ front_category-> newsTop5 as $ news) – sanu