Сортировка списка пользователей в Laravel - PullRequest
0 голосов
/ 23 октября 2019

Я очень новичок в Laravel. У меня Laravel 5.8 в моем проекте.

У меня есть этот код:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->char('enable', 1)->default(0);
            $table->string('name', 120)->nullable();
            $table->string('surname', 120)->nullable();
            $table->string('email', 120)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            ........
            $table->rememberToken();
            $table->timestamps();
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        });


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); // 1-5
            $table->text('content');
            $table->dateTime('date_time');
            $table->ipAddress('ip');
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';

Как мне показать список пользователей:

  1. сортировать по номерукомментариев:

  2. отсортировать по количеству голосов, которыми обладает пользователь (комментарии-> рейтинг)?

Ответы [ 2 ]

1 голос
/ 23 октября 2019

Попробуйте это

//User model

public function comments()
{
    return $this->hasMany('App\Comment');
}

public function usersSortedByCommentCount()
{
    $users = User::with('comments')->get()->sortBy(function($user)
    {
        return $user->comments->count();
    });

    return $users;
}

public function usersSortedByRating()
{
    return User::whereHas('comments', function ($q) {
        $q->orderBy('rating', 'desc');
    })->get();
}
0 голосов
/ 23 октября 2019
$users_sorted_by_comments = User::with('comments')->get()->sortBy(function($user){
 return $user->comments->count();
})

Другое условие очень похоже, вам нужно загрузить оценки для комментариев, а затем просто отсортировать по этому количеству следующим образом:

$users_sorted_by_ratings_on_comments = User::with('comments')->get()->sortBy(function($user){
 return $user->comments->reduce(function($carry, $comment) {
  return $carry + $comment->rating;
}, 0 );
})

Снижение Laravel Collection

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...