У меня есть две таблицы 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');
}
Любая помощь будет заметна.
Я предпочел решение в Красноречиво. Если это невозможно, другой способ тоже будет.
Спасибо, брат. Метод 'withCount()' для меня является новым. – smartrahat