laravel 5.1 多对多关系

laravel 5.1 many to many relation

嗨,这是我在 Laravel 5.1 的第一个项目。我陷入了 laravel 多对多关系中,请帮忙 我有一个 table 喜欢

新闻

编号 |标题 |内容

类别

编号 |标题 | cat_type

和枢轴table

category_news

编号 | category_id | news_id

和模特

 class News extends Model
{
   public function categories()
    {
        return $this->belongsToMany('App\Category');
    }
}

 class Category extends Model
{
   public function news() {

    return $this->belongsToMany('App\News');

  } 
}

如何获取 cat_type=1 的所有新闻及其相关类别

请帮忙

我试过了

$news = News::whereHas('categories',
           function($query){    
              $query->where('cat_type','2');    
            })
            ->where('publish','1')
            ->orderBy('created_at', 'desc')
            ->take(5)
            ->get();//latest news

它给出了一个新闻但不是相关的类别 请帮忙 谢谢

你可以先查询Category like

$category = Category::where('cat_type',2)->first();
$news = $category->news()->where->where('publish','1')
        ->orderBy('created_at', 'desc')
        ->take(5)
        ->get();

您也可以根据需要使用预加载

在这种情况下,您要做的就是编写如下内容:

$categoryAndNews = Category::with('news')->where('cat_type',2)->first();

您还可以在关系上下文中定义约束。

$categoryAndNews = Category::with(['news' => function($query){
    $query->orderBy('created_at', 'desc')
    ->take(5);
}])->get();

希望有用!

有关此主题的更多详细信息:http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads