按评论最多的文章排序

Sort articles by most comments

我有两个 tables articlescomments。有一对多的关系。一篇文章有​​很多评论,另一边评论属于一篇文章。现在我想根据大多数评论对所有文章进行排序。

这是 table 架构:

文章

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->integer('category_id')->unsigned();
        $table->text('body');
        $table->string('tags');
        $table->string('slug')->unique();
        $table->string('image');
        $table->date('published_at');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
    });
}

评论

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('blog_id')->unsigned();
        $table->integer('user_id')->unsigned();
        $table->integer('comment_id')->nullable(); //parent comment's id if any
        $table->text('message');
        $table->timestamps();

        $table->foreign('blog_id')
            ->references('id')
            ->on('articles')
            ->onDelete('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users');
    });
}

关系代码如下:

文章

/**
 * An article has many comments
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function comments()
{
    return $this->hasMany('App\Comment');
}

评论

/**
 * A comment is belongs to an article
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function article()
{
    return $this->belongsTo('App\Article');
}

任何帮助都将不胜感激。

I preferred the solution in Eloquent way. If not possible other way will also OK.

您可以试试:

Article::withCount('comments')->orderBy('comments_count')->get();

withCount() 方法用于计算关系的结果数而不实际加载它们,这将在结果模型上放置一个 {relation}_count 列。