[英]Laravel get count from model relationship
我有這3個模型。
Author
|id|name|
Post
|id|author_id|
Likes
|id|post_id|
關系。
作者
public function post()
{
return $this->hasMany(Post::class, 'author_id', 'id');
}
郵政
public function author(){
return $this->belongsTo(Author::class, 'id', 'author_id');
}
public function likes(){
return $this->hasMany(Likes::class, 'post_id', 'id');
}
喜歡
public function post()
{
return $this->belongsTo(Post::class, 'id', 'post_id');
}
我的問題是,如何列出所有作者的所有帖子中的總點贊數。
使用 call $authors->posts->likes 會導致錯誤,因為posts 返回一個集合。
作者有很多帖子,帖子有很多贊。
要從Author模型中獲得所有喜歡,您可以定義hasManyThrough()關系:
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...
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.