记录:一个模型关联多个模型,进行查询 代码示例:
protected $relationSearch = false;
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){
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');
}
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 时,以关联表为主表进行查询,未关联到也会显示
(持续更新中…)
|