一、关联统计
1、使用withCount()方法,可以统计主表关联附表的个数,输出用profile_count;
$list=Students::withCount(['stumenu'])->select([20,21,11]);
foreach($list as $user){
echo $user->stumenu_count;
}
2、关联统计的数据采用“关联方法名”_count,这种结构输出
3、还支持withMax、withMin、withSum、withAvg等
4、除了withCount()不需要指定字段,其它均需要指定统计字段;
$list=Students::withSum(['stumenu','price'])->select([11,112,25]);
foreach($list as $user){
echo $user->stumenu_sum;
5、对于输出的属性,可以自定义
$list = Students::withSum(['profile'=>'p_s'], 'status')->select([19,20,21]);
foreach ($list as $user) {
echo $user->p_s.'<br>';
}
二、关联输出
1、使用hidden()方法,隐藏主表字段或附表的字段
$list = Students::with('profile')->select();
return json($list->hidden(['profile.status']));
//或:
return json($list ->hidden(['username','password','profile'=>['status','id']]));
2、使用visible()方法,只显示相关的字段
$list->visible(['stumenu.sex']);
3、使用append()方法,添加一个额外字段,比如另一个关联的对象模型
$list->append(['book']);
本文详细介绍了ThinkPHP6.0中模型的关联统计和输出方法,包括使用withCount统计关联表数量,withMax、withMin、withSum、withAvg等聚合函数,以及如何自定义输出属性。在关联输出部分,讲解了如何隐藏和显示字段,以及利用append方法添加额外字段。
403

被折叠的 条评论
为什么被折叠?



