I have no idea how to solve this problem using Laravel Eloquent. So, I posted my question here.
I have tables like this:
+-------------+ +------------------------+
| POSTS | | COMMENTS |
|-------------| |------------------------|
| id | title | | id | text | post_id |
|-----+-------| |----+-------------------|
| 1 | A | | 1 | Lorem | 1 |
| 2 | B | | 2 | Ipsum | 1 |
+-------------+ | 3 | Dolor | 1 |
| 4 | Sit | 1 |
| 5 | Amet | 2 |
| 6 | Lorem 2 | 2 |
+------------------------+
I currently have 2 models, Post model
class Post extends Model
{
public function comment() {
$this->hasMany('App\Comment');
}
}
and Comment model
class Comment extends Model
{
public function comment() {
$this->belongsTo('App\Post');
}
}
The question is, What should I do on the controller so I can make each post has a comment count result? Or simply, just like the table below.
+-----------------------------------------+
| COMMENT COUNT |
|-----------------------------------------|
| posts.id | count(comments.post_id) AS n |
|----------+------------------------------|
| 1 | 4 |
| 2 | 2 |
+-----------------------------------------+
Thanks.