Thinkphp 6.0关联统计和输出

本节课我们来了解关联模型中,统计和输出的方法;
一.关联统计
1. 使用 withCount() 方法,可以统计主表关联附表的个数,输出用 profile_count
$list = UserModel::withCount(['profile'])->select([19,20,21]);
foreach ($list as $user) {
echo $user->profile_count;
}

2. 关联统计的输出采用“关联方法名”_ count,这种结构输出;

3. 不单单支持 Count,还有如下统计方法,均可支持;

4. withMax() withMin() withSum() withAvg()等;
5. 除了 withCount() 不需要指定字段,其它均需要指定统计字段;
$list = UserModel::withSum(['profile'], 'status')->select([19,20,21]);
foreach ($list as $user) {
echo $user->profile_sum.'<br>';
}
6. 对于输出的属性,可以自定义:
$list = UserModel::withSum(['profile'=>'p_s'], 'status')->select([19,20,21]);
foreach ($list as $user) {
echo $user->p_s.'<br>';
}
二.关联输出
1. 使用 hidden() 方法,隐藏主表字段或附属表的字段;
$list = UserModel::with('profile')->select();
return json($list->hidden(['profile.status']));
或:
return json($list
->hidden(['username','password','profile'=>['status','id']]));
2. 使用 visible() 方法,只显示相关的字段;
$list->visible(['profile.status'])
3. 使用 append() 方法,添加一个额外字段,比如另一个关联的对象模型;
$list->append(['book])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值