laravel 使用 ORM 写复杂 sql
直接先贴出 sql 查询语句如下
SELECT
`assets_device`.*
FROM
(
(
SELECT
`id`,
`sub_category_id`,
`number`,
`name`,
`location`,
`officeBuilding`,
`area`,
`department`,
`rack`,
`rack_pos`
FROM
`assets_device`
WHERE
`department` IN ( 6, 7, 17, 20 )
AND `assets_device`.`deleted_at` IS NULL
) UNION
(
SELECT
`id`,
`sub_category_id`,
`number`,
`name`,
`location`,
`officeBuilding`,
`area`,
`department`,
`rack`,
`rack_pos`
FROM
`assets_device`
WHERE
`area` IN ( 13, 14 )
AND `assets_device`.`deleted_at` IS NULL
)
) AS assets_device
实现代码如下所示
public function getChoiceAssetsByErOrDt($request){
$input = $request->input();
if(isset($input['er'])){
if(is_array($input['er'])){
$erIds = $input['er'];
}else{
$erIds = explode(',',$input['er']);
}
}else{
$erIds = array();
}
if(isset($input['dt'])){
if(is_array($input['dt'])){
$dtIds = $input['dt'];
}else{
$dtIds = explode(',',$input['dt']);
}
}else{
$dtIds = array();
}
$field = ['id','sub_category_id','number','name','location','officeBuilding','area','department','rack','rack_pos'];
if($erIds){
$erModel = $this->deviceModel->select($field)
->whereIn('area',$erIds);
}
if($dtIds){
$dtModel = $this->deviceModel->select($field)
->whereIn('department',$dtIds);
}
$model = $dtModel->union($erModel);
$data = $this->deviceModel->with('sub_category','zone','office_building','engineroom','department')
->mergeBindings($model->getQuery())
->select(["assets_device.*"])
->from(DB::raw("({$model->toSql()}) as assets_device"))
->withTrashed()
->orderBy('assets_device.id')
->paginate()
->toArray();
foreach ($data['data'] as &$val){
$val['department_name'] = isset($val['department']['name']) ? $val['department']['name'] : '';
$val['sub_category_name'] = isset($val['sub_category']['name']) ? $val['sub_category']['name'] : '';
$val['zone_name'] = isset($val['zone']['name']) ? $val['zone']['name'] : '';
$val['office_building_name'] = isset($val['office_building']['name']) ? $val['office_building']['name'] : '';
if(isset($val['engineroom']['name'])){
$erdt = $val['engineroom']['name'];
}elseif (isset($val['department']['name'])){
$erdt = $val['department']['name'];
}else{
$erdt = null;
}
$val['erdt'] = $erdt;
unset($val['department']);
unset($val['sub_category']);
unset($val['zone']);
unset($val['office_building']);
unset($val['engineroom']);
unset($val['department']);
}
return $data;
}