gwebme
gwebme

Reputation: 3

Laravel Relationship between 3 tables

so I am trying to get the category name and this is what I have tablets:

categories: id,name

post_categories: id, post_id, category_id

post : id, columns

I have the models: Post, PostCategory and Category.

Post Model :

public function categories()
{
    return $this->hasMany('App\PostCategory');
}

PostCategory Model :

public function category()
{
    return $this->hasMany(Category::class, 'id', 'category_id');
}

and in the controller I have

return Post::with('categories.category')->orderby('id','desc')->get();

And my result is

 [
  {
    "id": 50,
    "categories": [
      {
        "id": 92,
        "category_id": 11,
        "category": [
          {
            "id": 11,
            "name": "JXrfLHdQVNON",
            "image": null
          }
        ]
      }
    ]
  }
]

and i wanted it to be something like

[
  {
    "id": 50,
    "categories": [
      {
        "id": 1,
        "name": "category_name",
        "image": null
      }
    ]
  }
]

Is there a way to do it? I have been playing around with this and havent manage to find a easy way to do it

Upvotes: 0

Views: 182

Answers (2)

Saurabh Mistry
Saurabh Mistry

Reputation: 13699

inside your Post model :

 public function categories()
 {
        return $this->belongsToMany('App\Model\Category','post_categories','post_id','category_id')->withTimestamps();
 }

in your controller :

return Post::with('categories:id,name,image')->orderBy('id','desc')->get();

Upvotes: 1

Adis Azhar
Adis Azhar

Reputation: 1022

This is a many-to-many relationship. Make sure you have your relationship set up correctly. If you want to choose specific columns you can do:

return Post::with('categories.category:id,name')->orderby('id','desc')->get();

It will return the columns id, name from category table/ model. You must specify id doing that.

https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

https://laravel.com/docs/5.7/eloquent-relationships#eager-loading

Upvotes: 0

Related Questions