Laravel项目统计用户对应记录数时报错:Attempt to read property "location" on int
问题解决:Attempt to read property "location" on int
错误原因
你在循环中执行了{{$user = DB::table('kinds')->count()}},这行代码会把原本的用户对象覆盖成一个整数(整个kinds表的总记录数)。后续代码调用$user->location时,自然会触发"在整数上读取属性"的错误——因为整数类型根本没有location属性。
正确解决方案
方法1:使用Eloquent关联统计(推荐)
这种方式更符合Laravel的最佳实践,性能也更好。
- 定义模型关联
在app/Models/User.php中添加和kinds表的一对多关联:
public function kinds() { // 假设kinds表的外键是user_id,关联到users表的id return $this->hasMany(\App\Models\Kind::class); }
- 控制器预加载统计数据
在查询用户列表时,用withCount预加载每个用户对应的kinds行数:
// 控制器对应的方法 $users = \App\Models\User::withCount('kinds')->get();
- 视图中直接调用统计值
把视图里错误的统计代码替换成:
{{ $user->kinds_count }}
这样不会覆盖原有的$user对象,后续的$user->location、$user->created_at等属性都能正常访问。
方法2:直接查询单用户的行数(不推荐,性能较差)
如果暂时不想用模型关联,也可以直接查询当前用户对应的kinds行数,但绝对不要覆盖$user变量:
{{ DB::table('kinds')->where('user_id', $user->id)->count() }}
修改后的视图关键代码片段
@foreach($users as $user) <div class="d-inline p-2"> <div class="col"> <div class="card" style="width: 18rem;"> <!-- 其他代码不变 --> <small><i class="fa fa-building-o" style="color:#3490dc;"></i> {{$user->organization}}</small> <br/> <!-- 替换成正确的统计代码 --> {{ $user->kinds_count }} <br/> <small><small><i class="fa fa-map-marker" style="color:#3490dc;"></i> {{$user->location}}</small> </small><br/><hr color=3490dc> <!-- 其他代码不变 --> </div> </div> </div> <br/> @endforeach
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

