我的Laravel版本是11。我执行以下代码能正常获得查询结果:
$topic_users = DB::table('topics')->select(DB::raw('user_id, count(*) as topic_count'))->where('created_at', '>=', Carbon::now()->subDays(60))->groupBy('user_id')->get();
或
$topic_users = DB::table('topics')->selectRaw('user_id, count(*) as topic_count')->where('created_at', '>=', Carbon::now()->subDays(60))->groupBy('user_id')->get();
但执行以下代码:
$topic_users = Topic::select(DB::raw('user_id, count(*) as topic_count'))->where('created_at', '>=', Carbon::now()->subDays(60))->groupBy('user_id')->get();
或
$topic_users = Topic::query()->select(DB::raw('user_id, count(*) as topic_count'))->where('created_at', '>=', Carbon::now()->subDays(60))->groupBy('user_id')->get();
或
$topic_users = Topic::selectRaw('user_id, count(*) as topic_count')->where('created_at', '>=', Carbon::now()->subDays(60))->groupBy('user_id')->get();
报错:
Illuminate\Database\Eloquent\MissingAttributeException The attribute [view_count] either does not exist or was not retrieved for model [App\Models\Topic].
该错误的原因是在使用Topic模型执行查询时,Laravel Eloquent默认会尝试加载模型中声明的所有属性(即数据库表中的所有列),但是你的查询语句是聚合查询,只返回user_id和聚合字段topic_count。Laravel Eloquent默认会尝试加载Topic模型中的所有字段,期望你返回的是一个“普通”的字段列表,而不是聚合后的结果,因此出现了MissingAttributeException错误,因为在查询结果中并没有view_count字段。