记录:一个模型关联多个模型,进行查询
代码示例:
protected $relationSearch = false;/*** @NodeAnotation(title="列表")*/public function index(){ if ($this->request->isAjax()) {if (input('selectFields')) {return $this->selectList();}list($page, $limit, $where) = $this->buildTableParames();$count = $this->model->withJoin(['systemCar','driver','supplier'],'left') ->where($where)->count();$list = $this->model->withoutField('delete_time')->withJoin(['systemCar','driver','supplier'],'left')->where($where)->page($page, $limit)->order($this->sort)->select()->each(function($item,$key){//创建人类型:1-管理员,2-客户if($item['create_people_type'] == 1){$item['create_people'] = Db::name('system_admin')->where(['id'=>$item['create_people']])->value('realname');}else{$item['create_people'] = Db::name('customer')->where(['id'=>$item['create_people']])->value('name');}//修改人类型:1-管理员,2-客户if($item['update_people_type'] == 1){$item['update_people'] = Db::name('system_admin')->where(['id'=>$item['update_people']])->value('realname');}else{$item['update_people'] = Db::name('customer')->where(['id'=>$item['create_people']])->value('name');}$item['create_time'] = $item['create_time'] ? date('Y-m-d H:i:s',$item['create_time']) : ''; $item['update_time'] = $item['update_time'] ? date('Y-m-d H:i:s',$item['update_time']) : ''; //开始配送时间,预计到达时间$item['start_time'] = $item['start_time'] ? date('Y-m-d H:i:s',$item['start_time']) : ''; $item['end_time'] = $item['end_time'] ? date('Y-m-d H:i:s',$item['end_time']) : ''; });$data = ['code' => 0,'msg' => '','count' => $count,'data' => $list,];return json($data);}return $this->fetch();}
注意:
1,withJoin([‘systemCar’,‘driver’,‘supplier’],‘left’) 要放在withoutField() 函数之后
2,withJoin([‘systemCar’,‘driver’,‘supplier’],‘left’) 中第二个参数:
a/ 不填时,若未关联到数据时,则不显示
b/ 为 left 时,以当前表为主表进行查询,未关联到也会显示
c/ 为 right 时,以关联表为主表进行查询,未关联到也会显示
二、查询并显示关联表中的部分字段
->with(['pinpai'=>function($query){$query->field('pinpai.id as pinpaiid,pinpai_name');}])
(持续更新中…)