dsf4354353452 2016-05-16 08:14
浏览 50
已采纳

Eloquent:根据表关系计算行数

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.

  • 写回答

1条回答 默认 最新

  • dsjhejw3232 2016-05-16 08:23
    关注

    You forgot to return the relationships. So, the models should be defined as:

    class Post extends Model
    {
        public function comments()
        {
            return $this->hasMany('App\Comment');
        }
    }
    
    class Comment extends Model
    {
        public function post()
        {
            return $this->belongsTo('App\Post');
        }
    }
    

    Now you can count the post comments as:

    echo $post->comments()->count();
    

    or even

    echo $post->comments->count();
    

    The difference between these 2 methods is that the latest one is getting and caching the post comments as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?