2016-10-28 3 views
0

У меня есть две таблицы articles и comments. У них есть одно отношение. В статье много комментариев, а с другой стороны комментарий принадлежит статье. Теперь я хочу отсортировать все статьи в соответствии с большинством комментариев.Сортировка статей по большинству комментариев

Вот схема таблицы:

статьи

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'); 
} 

Любая помощь будет заметна.

Я предпочел решение в Красноречиво. Если это невозможно, другой способ тоже будет.

ответ

2

Вы можете попробовать, как:

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

withCount() метод используется, когда вы хотите, чтобы подсчитать количество результатов отношений фактически не загружая их, что поместит {отношение} _count колонки на вашем в результате модели.

+0

Спасибо, брат. Метод 'withCount()' для меня является новым. – smartrahat

Смежные вопросы