我被困在这里一直试图从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