简体   繁体   中英

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.

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...
   );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM