laravel - 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();
});
}
请问怎么解决?
解决方案
如果您正在寻找顶级用户(帖子最多的用户),那么从用户模型的角度来看可能会更容易。因此,从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');
推荐阅读
- android - 当他的购物车为空时,我如何向用户显示消息,我正在使用 RecyclerAdapter 来显示购物车项目
- python - 返回从列表中选择的大小 n 组合的递归函数
- javascript - 在 Vue.js 中,为什么我的计算属性不起作用
- swift - 无法从 firebase 实时数据库中获取/读取数据到 UITableViewController
- typescript - 打字稿:从 {} 扩展
- python - 如何解决“hape 必须是 2 级,但对于 'MatMul_4'(操作:'MatMul')来说是 0 级,输入形状:[],[3]。”
- django - 从 vuejs 和 Django 后端将文件上传到 s3
- django - 如何在 Django 中使用下拉项创建表单?
- html - 如果没有高度的像素值,我的背景图像不会加载
- python - 如何处理 BigQuery Stream Pipeline 中的非 ascii 字符?