I have standard Post & Comments hasMany relation
class Post extends Model
{
// @property int $id
// @property string $title
// @property string $author_id
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
// @property int $id
// @property int $post_id
// @property int $user_id (author ids + guests ids)
// @property string $content
public function post()
{
return $this->belongsTo(Post::class);
}
}
Post can have author and guests comments so user_id field in comments table can contain author_id and guest_ids.
| id | post_id | user_id | content |
| — | ——- | ——- | ————– |
| 1 | 1 | 1 | author comment |
| 2 | 1 | 2 | guest1 comment |
| 3 | 1 | 1 | author comment |
| 4 | 1 | 3 | guest2 comment |
| 5 | 1 | 2 | guest1 comment |
I need to get posts list with eager loaded comments count for author and for guests, so my question is:
How can I get the count of author comments (author_comments_count = 2) and the count of guests comments (guests_comments_count = 3) using withCount()
Thank you in advance