0
私は2つのテーブルarticles
とcomments
を持っています。 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です。
ありがとうございました。 'withCount()'メソッドは私にとっては新しいものです。 – smartrahat