laravel中有条件使用where

时间:2021-05-19 22:16:51

在项目开发的过程中;有时候会有多个参数 去用在where查询中;那么这里的where语句是可能有也可能没有的

1.用原生的mysql语句来实现

private function getData($type, $status, $data_id, $start_time, $end_time, $size, $page, $id)
    {
        $type = trim($type);
        $status = trim($status);
        $data_id = trim($data_id);
        $start_time = strtotime(trim($start_time)); // 转换为uninx时间戳
        $end_time = strtotime(trim($end_time));
        $size = trim($size);
        $page = trim($page);
        $id = trim($id);

        $where = ' where 1=1';
        if ($type) {
            $where .= " AND dp.task_type = $type";
        }
        if ($status) {
            $where .= " AND d.data_status = $status";
        }
        if ($data_id) {
            $where .= " AND d.id = '$data_id'";
        }
        if ($start_time) {
            $where .= " AND d.dial_time >= $start_time";
        }
        if ($end_time) {
            $where .= " AND d.dial_time <= $end_time";
        }
        if ($id) {
            $where .= " AND b.id = $id";
        }

        $sql = "SELECT d.id,d.dial_time,d.time_len,d.record,d.called_phone  FROM a_data as d LEFT JOIN a_data_packet as dp ON d.data_packet_id = dp.id LEFT JOIN a_business as b ON dp.business_id = b.id ";
        $sql .= $where;
        $sql .= ' order by dial_time desc';
        $sql .= " limit ".($page-1)*$size.", $size"; // 偏移量,每一页显示几条
        $res = DB::select($sql);

        return $res;
    }

 

2.用laravel的where语句来实现

private function getExtData($status, $data_id, $all_extract)
    {
        $db = \AiBusiness\Models\Data::select('id', 'dial_time','time_len', 'kh_phone')->where('data_status', $status);
        if ($all_extract == 1) {
            if ($data_id) {
                $db->whereIn('id', $data_id);
            }
        }
        $extract_data = $db->get();

        return $extract_data;
    }