我怎样才能从一对多的关系中获取数据

How can i get data from relationship one to many

我是 Laravel 5 的新人,我需要一些帮助, 我有两个模型(post 和 category )具有一对多关系(类别有很多 posts ),我只需要获得影响 posts 的类别。

示例:

    ****category
    id_cat       nom_cat

     1           cat1
     2           cat2
     3           cat3
     4           cat4

    post 

    id_post     nom_post    id_cat**
      1           post1        1
      2           post2        1
      3           post3        4

   result 

    id_cat    nom_cat  
      1         cat1      
      4         cat4**

谢谢

假设帖子只有一个类别。每个类别都有很多相关的帖子。

声明关系。

Post 型号:

public function category()
{
    return $this->belongsTo(Category::class);
}

类别模型:

public function posts()
{
    return $this->hasMany(Post::class);
}

然后你可以得到他们有帖子的类别。

$categories = App\Category::has('posts')->get();