2016-10-28 8 views
0

私は2つのテーブルarticlescommentsを持っています。 1対1の関係を持っています。記事には多くのコメントがあり、反対側には記事に属するコメントがあります。今私はほとんどのコメントに従ってすべての記事を並べ替えたいここでほとんどのコメントで記事を並べ替え

は、テーブルのスキーマです:

記事ここ

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

すべてのヘルプはかなりの量になります。

私は、優しい方法で溶液を選ぶことをお勧めしました。可能でない場合は他の方法もOKです。

答えて

2

あなたに試すことができます。

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

withCount()方法が使用されている、あなたが実際にそれらをロードすることなく関係からの結果の数をカウントしたい場合、上の{関連} _count列が配置されますされ、あなたの結果として生じるモデル。

+0

ありがとうございました。 'withCount()'メソッドは私にとっては新しいものです。 – smartrahat

関連する問題