luca ditrimma
luca ditrimma

Reputation: 855

Laravel get count from model relationship

I have this 3 model.

Author
|id|name|

Post
|id|author_id|

Likes
|id|post_id|

The relationship.

Author

public function post()
{
    return $this->hasMany(Post::class, 'author_id', 'id');                                             
}

Post

public function author(){
    return $this->belongsTo(Author::class, 'id', 'author_id');
}

public function likes(){
    return $this->hasMany(Likes::class, 'post_id', 'id');
}

Likes

public function post()
{
    return $this->belongsTo(Post::class, 'id', 'post_id');
}

My problem is, how to list all Authors with total likes from all of his posts.

Using call $authors->posts->likes results an error because posts returns a collection.

Upvotes: 1

Views: 132

Answers (1)

STA
STA

Reputation: 34688

Author hasMany posts, and Post hasMany likes.
To achieve all likes from the Author model, you can define a hasManyThrough() relationship :

public function likes()
{
   return $this->hasManyThrough(
       'App\Likes', // Likes model
       'App\Post', // Post model
       'author_id', // Foreign key on posts table...
       'post_id', // Foreign key on likes table...
       'id', // Local key on authors table...
       'id' // Local key on posts table...
   );
}

Upvotes: 1

Related Questions