У меня есть 2 таблицы: пользователи и комментарии.
Каждый комментарий имеет оценку. Один пользователь может иметь много комментариев.
Это моя миграция
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
......
});
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('commentable_type');
$table->bigInteger('commentable_id');
$table->char('enable', 1)->default(0);
$table->char('to_stats', 1)->default(0);
$table->tinyInteger('rating')->default(0);
...
});
Comment.php
class Comment extends Model
{
...
public function commentable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo('App\User');
}
}
User.php
class User extends Authenticatable implements MustVerifyEmail
{
...
public function comments()
{
return $this->hasMany('App\Comment');
}
public function commentsReceived()
{
return $this->hasMany('App\Comment', 'commentable_id', 'id');
}
public function scopeOfRoleType($query, $types)
{
return $query->whereHas('roles', function ($q) use ($types) {
$q->whereIn('name', $types);
});
}
public function userRatingCount()
{
return $this->hasMany('App\Comment', 'commentable_id', 'id')->where('enable', '=', '1')->where('to_stats', '=', '0');
}
}
Я хочу показать список пользователей, упорядоченный по итоговому столбцу рейтинга в таблице комментариев (скажем так, голоса). Затем мне нужно отобразить его от большинства голосов до самых маленьких.
Я пробую этот код, но он не работает:
$users = User::ofRoleType($role)->with('userRatingCount')->sum('comments.rating');
Как это исправить?