我想显示回答调查的前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();
});
}
请问如何解决?
答案 0 :(得分:2)
如果您正在寻找高级用户(帖子数量最多的用户),从 User 模型角度来看可能会更容易。因此,从 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');
答案 1 :(得分:0)
你可以这样做
public function topuser()
{
$bestuser = Answer::OrderBy('created_at', 'DESC')->take(10)->get();
return view('dashboard.top')->with('bestuser', $bestuser);
}