TP5的Union查询
< 返回列表时间: 2020-06-29来源:OSCHINA
union的用法
需求
:联合两个记录表做一个类似时间轴的东西,因为要排序和分类,unionAll $field = [ 't.create_time', 'h.unit', 'h.door', 'h.build_id', ]; $where = [ ['t.creater_id', '=', $admin_id], ['t.company_id', '=', $userInfo['company_id']], ['t.if_delete', '=', 0], ]; $temp_field = $field; $temp_field['content'] = 'message'; $temp_field[] = '0 as policy_id'; $temp_field[] = '1 as source'; $temp_field[] = 'record_id as id'; $res = Db::field($temp_field) ->table(KpurposeRecord::instance()->getTable()) ->alias('t') ->join('k_house h', 'h.house_id=t.house_id and h.if_delete = 0', 'left') ->where($where) ->unionAll(function ($query) use ($admin_id, $field, $where) { $temp_field = $field; $temp_field[] = 'message'; $temp_field[] = 'policy_id'; $temp_field[] = '2 as source'; $temp_field[] = 'reserve_id as id'; $query->field($temp_field) ->table(Kreservation::instance()->getTable()) ->alias('t') ->join('k_house h', 'h.house_id=t.house_id and h.if_delete = 0', 'left') ->where($where); }); $res->order('create_time', 'desc'); if (!empty($page) && !empty($limit)) { $res->page($page, $limit); } $list['customer_development'] = $res->select();
PS
field字段顺序要一致,不然数据会错乱 最后,应尽量避免这种操作,写法麻烦,查询效率还不高
热门排行