user3514348
user3514348

Reputation: 59

How can i get data from relationship one to many

I'm new in Laravel 5 and i need some help, I have two models (post and category ) with one to many relationship ( category has many posts ) and i need to get only categories which has posts affected.

example:

    ****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**

thanks

Upvotes: 0

Views: 37

Answers (1)

Leo
Leo

Reputation: 7420

Lets say posts they have only one category. And each category has many posts related.

declare the relationships.

Post model:

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

Category model:

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

then you can get categories that they do have posts.

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

Upvotes: 1

Related Questions