模型预载入查询 筛选 统计
模型里
public function profile()
{
return $this->hasMany(Profile::class);
}
使用的地方 类里
public function index()
{
// 普通查询 有多少条数据 foreach就会获取多少次 + 1次数据
// $users = Users::select();
// foreach ($users as $user) {
// echo $user->profile;
// }
// 预载入查询 只会查询两次表
// ['profile'] 可以查询多个表
// $users = Users::with(['profile'])->select();
// foreach ($users as $user) {
// echo $user->profile;
// json($user->profile);
// }
// 表里字段过多 可以自定义要 visible显示 或者 hidden隐藏 的字段
// $users = Users::with(['profile'])->select();
// profile.hobby profile是副表 hobby是副表里的字段 只显示副表的hobby字段
// $users->visible(['id', 'profile.hobby']);
// return json($users);
// 统计
// 关联统计 withCount 会自动统计出主表数据 对应的 关联副表的数据条数
// $users = Users::withCount(['profile'])->select();
// foreach ($users as $user) {
// echo $user->profile_count;
// }
}