75.关联统计和输出
学习要点:1.关联统计2.关联输出本节课我们来了解关联模型中,统计和输出的方法;一.关联统计1.使用withCount()方法,可以统计主表关联附表的个数,输出用profile_count;$list=UserModel::withCount('profile')->all([19,20,21]);foreach($listas$user){echo$user->profile_count;}2.3.4.5.关联统计的输出采用“关联方法名”_count,这种结构输出;不单单支持Count,还有如下统计方法,均可支持;withMax()、withMin()、withSum()、withAvg()等;除了withCount()不需要指定字段,其它均需要指定统计字段;$list=UserModel::withSum('profile','status')->all([19,20,21]);foreach($listas$user){echo$user->profile_sum.'
';}6.对于输出的属性,可以自定义:$list=UserModel::withSum(['profile'=>'p_s'],'status')->all([19,20,21]);foreach($listas$user){echo$user->p_s.'
';}二.关联输出1.使用hidden()方法,隐藏主表字段或附属表的字段;$list=UserModel::with('profile')->select();returnjson($list->hidden(['profile.status']));或:returnjson($list->hidden(['username','password','profile'=>['status','id']]));2.使用visible()方法,只显示相关的字段;$list->visible(['profile.status'])3.使用append()方法,添加一个额外字段,比如另一个关联的对象属性;$list->append(['book.title'])
相关推荐: