karhu
karhu

Reputation: 119

How do I get a field from a sub-relation in Laravel?

Objective:

Include category_name field in $posts attributes. The corresponding FK - category_id is currently included in my return.

Controller returns all Posts with their PostChilds

return $posts = Post::with('postchildren')->get();

Post Model hasMany PostChild

public function postchildren() {
    $this->hasMany('App\PostChild')
}

PostChild Model hasOne Category

(This table has a category_id field which is a FK for id in the Category model.)

 public function category() {
    $this->hasOne('App\Category');
 }

Category Model

This table has a category_name field

Upvotes: 1

Views: 1149

Answers (1)

owenmelbz
owenmelbz

Reputation: 6584

You should be able to get all the categories associated with the children via the HasManyThrough relationship e.g.

class Post
{
    public function categories()
    {
        return $this->hasManyThrough(PostChild::class, Category::class);
    }
}

Then you can access the categories directly on the post object e.g.

$categories = Post::first()->categories;

or if you're wanting an array of them something like

$posts = Post::with('categories')->get();

If you always want the categories loaded on the Post class you can define

class Post
{
    protected $with = ['categories'];

Upvotes: 1

Related Questions