Php 在Laravel中排序用户列表

Php 在Laravel中排序用户列表,php,laravel,laravel-5,Php,Laravel,Laravel 5,我是拉雷维尔的初学者。 我的项目中有Laravel 5.8 我有以下代码: Schema::create('users',函数(Blueprint$表){ $table->bigIncrements('id'); $table->char('enable',1)->默认值(0); $table->string('name',120)->nullable(); $table->string('姓氏',120)->nullable(); $table->string('email',120)->un

我是拉雷维尔的初学者。 我的项目中有Laravel 5.8

我有以下代码:

Schema::create('users',函数(Blueprint$表){
$table->bigIncrements('id');
$table->char('enable',1)->默认值(0);
$table->string('name',120)->nullable();
$table->string('姓氏',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',函数(Blueprint$表){
$table->bigIncrements('id');
$table->biginger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('commentable_type');
$table->biginger('commentable_id');
$table->char('enable',1)->默认值(0);
$table->char('to_stats',1)->默认值(0);
$table->tinyInteger('rating')->默认值(0);//1-5
$table->text('content');
$table->dateTime('date\u time');
$table->ipAddress('ip');
$table->engine=“InnoDB”;
$table->charset='utf8mb4';
$table->collation='utf8mb4_unicode_ci';
如何显示用户列表:

  • 按保留的评论数排序

  • 按用户的投票数排序(评论->评分)

  • 试试这个

    //用户模型
    公共职能评论()
    {
    返回$this->hasMany('App\Comment');
    }
    公共函数usersSortedByCommentCount()
    {
    $users=User::with('comments')->get()->sortBy(函数($User)
    {
    返回$user->comments->count();
    });
    返回$users;
    }
    公共函数usersSortedByRating()
    {
    返回用户::whereHas('comments',函数($q){
    $q->orderBy('rating','desc');
    })->get();
    }
    另一个条件非常类似,您需要在评论上加载评级,然后按照该计数进行排序,如下所示:

    $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 );
    })
    
    

    好的,这很有效。我如何根据用户拥有的投票数(评论->评分)进行排序?我有错误:在模型[App\Comment]上调用未定义的关系[votes]。在模型[App\Comment]上没有调用未定义的关系[ratings]。没有问题:)现在这段代码运行了,但它没有正确排序您希望获得什么类型的输出,而不是它给您提供什么?dd(用户::whereHas('commentsReceived',function($q){$q->orderBy('rating','desc');})->get();-这不起作用:(
    $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 );
    })