php - laravel 根据留言表 查询出留言最多的文章,热度排行榜查询

查看:107
本文介绍了php - laravel 根据留言表 查询出留言最多的文章,热度排行榜查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

mysql 小白

希望查询出文章留言的 排行榜

希望找个大神 指导一下 。

comments 评论表

Schema::create('comments', function (Blueprint $table) {
      $table->increments('id');   
      $table->string('post_id')->notNull()->comment('文章id');
      $table->string('body')->notNull()->comment('留言内容');
      $table->timestamps();
});

posts 文章表

Schema::create('posts ', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title')->notNull()->comment('文章标题');
      $table->string('body')->notNull()->comment('文章内容');
      $table->timestamps();
});

demo

comments 表有如下数据

id post_id body
1 1 ?到此一游
2 2 此文嘉奖
3 1 ♥不错
4 2 ♥不错+1
5 1 ♥不错+2
6 1 ♥不错+3
7 1 ♥不错+4

最终希望查询出如下

post_id comment_count
1 5
2 2

解决方案

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

class Comment extends Model
{

}

$posts = Post::withCount('comments')->get()->sortBy('comments_count');

这篇关于php - laravel 根据留言表 查询出留言最多的文章,热度排行榜查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆