I'm using Laravel and MySQL, and I have a table post that represents post where users can comment on it, now I wanna order posts by the number of comments of each post in ascending/descending order, how do I do this in Laravel? I don't want to add a field in post table to keep track of the number of comments of each post, because updating that field manually each time a comment or a comment's comment is added/deleted drives me crazy...
This is how I create my posts table and comments table:
Schema::create('posts', function($table) {
$table->increments('id');
$table->string('title', 100)->unique();
$table->string('content', 2000);
$table->timestamps();
});
Schema::create('comments', function($table) {
$table->increments('id');
$table->string('content', 2000);
$table->unsignedInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('parent_id')->nullable();
$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
And this is how I setup relationship between posts and comments in my Post model:
public function comments() {
return $this->hasMany('Comment', 'post_id');
}
And in Comment model:
public function post() {
return $this->belongsTo('Post', 'post_id');
}