Article From:https://segmentfault.com/q/1010000010190465
Question:

mysql Small white

I hope to find out the ranking of the article messages.

I hope to find a great God to guide you.

comments Review table

Schema::create('comments', function (Blueprint $table) {
      $table->increments('id');   
      $table->string('post_id')->notNull()->comment('Article id');$table-> string ('body') -> notNull () -> comment ("message content");$table-> timestamPS ();});

posts Article table

Schema::create('posts ', function (Blueprint $table) {
      $table->increments('id');
      $table->string('title')->notNull()->comment('Article title ");$table-> string ('body') -> notNull () -> comment (' article content ');$table-> timestamPS ();});

demo

comments The table has the following data

idpost_idbody
11?Go to this tour
22This article Award
31♥Pretty good
42♥Good +1
51♥Good +2
61♥Good +3
71♥Good +4

Finally, I would like to check out the following

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

class Comment extends Model
{

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

Answer 1:

TrySELECT post_id,count(1) as comment_count FROM comments GROUP BY post_id ORDER BY comment_count LIMIT 10000

Leave a Reply

Your email address will not be published. Required fields are marked *