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