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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100