首页 > 解决方案 > Laravel:从答案的调查表中获取前 10 名用户

问题描述

我想显示回答调查的前 10 位用户

我试过这个

public function topuser()
{
    $bestuser = Answer::whereRaw('id = (select max(count(`id`)) from Answer)')->get();

    return view('dashboard.top')->with('bestuser', $bestuser);
}

但这给了我一个错误。

答案型号:

class Answer extends Model
{
    protected $fillable = ['answer'];
    protected $table = 'answer';

    public function survey() {
      return $this->belongsTo(Survey::class);
    }

    public function question() {
      return $this->belongsTo(Question::class);
    }
}

回答迁移文件:

public function up()
{
    Schema::create('Answer', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('question_id');
        $table->integer('survey_id');
        $table->string('answer');
        $table->timestamps();
    });
}

请问怎么解决?

标签: laravelauthentication

解决方案


如果您正在寻找顶级用户(帖子最多的用户),那么从用户模型的角度来看可能会更容易。因此,从User模型上的Answer关系中提取一个计数,如下所示:

$bestuser = User::withCount('answers as answer_count')
                 ->orderBy('answer_count', 'desc')
                 ->take(10)
                 ->get();

或者,如果您只想要一个简单的列表:

$bestuser = User::withCount('answers as answer_count')
                 ->orderBy('answer_count', 'desc')
                 ->take(10)
                 ->pluck('answer_count', 'name');

推荐阅读