thinkphp6.0模型篇之关联统计与输出

本文详细介绍了ThinkPHP6.0中模型的关联统计和输出方法,包括使用withCount统计关联表数量,withMax、withMin、withSum、withAvg等聚合函数,以及如何自定义输出属性。在关联输出部分,讲解了如何隐藏和显示字段,以及利用append方法添加额外字段。

一、关联统计

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']);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值