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');
}
任何幫助將是明顯的。
我喜歡用雄辯的方式解決問題。如果不行其他方式也行。
感謝兄弟。 'withCount()'方法對我來說是新的。 – smartrahat