如何将此查询转换为laravel语法以使用分页

时间:2018-08-29 00:21:03

标签: php sql laravel

$db = DB::connection()->getPdo();
$query = "
    SELECT 
    c.id, sys_id, cam_name, description, brand, product, c.status, update_by, start_date, end_date,  
    DATE_FORMAT(CONVERT_TZ(c.created_at, @@session.time_zone, '" . Common::utc_offset() . "'), '%Y-%m-%d %H:%i:%s') as created_at, 
    DATE_FORMAT(CONVERT_TZ(c.updated_at, @@session.time_zone, '" . Common::utc_offset() . "'), '%Y-%m-%d %H:%i:%s') as updated_at, 
    hashid, blm_field, inactive_period, is_testing, signature, camp_type,
    SUM(IF(p.inter = 1 AND p.admin_res = 0, 1, 0)) as Bi_count
    FROM camp c
    LEFT JOIN pros p on c.id = p.camp_id   "
;
if ($campaign_type != null) $query = $query . ' WHERE c.campaign_type = "' . $camp_type . '" ';
    $query = $query . ' GROUP BY c.id ';

    $excute= $db->prepare($query);

我真的是laravel的新手,所以想知道是否有一种方法可以将此查询转换为laravel语法以使用pagination()

2 个答案:

答案 0 :(得分:0)

假设您已经建立了Camp模型,则可以执行以下操作:

$db = Camp::selectRaw("c.id, sys_id, cam_name, description, brand, product, c.status, update_by, start_date, end_date,  
                DATE_FORMAT(CONVERT_TZ(c.created_at, @@session.time_zone, ?), '%Y-%m-%d %H:%i:%s') as created_at, 
                DATE_FORMAT(CONVERT_TZ(c.updated_at, @@session.time_zone, ?), '%Y-%m-%d %H:%i:%s') as updated_at, 
                hashid, blm_field, inactive_period, is_testing, signature, camp_type,
                SUM(IF(p.inter = 1 AND p.admin_res = 0, 1, 0)) as Bi_count", ['offset1' => Common::utc_offset(), 'offset2' => Common::utc_offset()])
->leftJoin('pros', 'camp.id', '=', 'pros.camp_id');

if($campaign_type != null){
    $db->where('campaign_type', $campaign_type);
}     

$db->GroupBy('camp.id');

$db = $db->paginate(10);

答案 1 :(得分:0)

好吧,因为您既没有使用Eloquent也没有使用Query构建器,所以您将不得不做一些额外的工作才能享受paginate()的强大功能。

使用Laravel的原始查询支持,请尝试以下操作:

$result = \DB::select($query);
$collection = collect($result);

然后使用以下两种方法对结果进行分页。

方法1

$chunk = $collection->forPage($pageNumber, $numberOfItemsPerPage);
dd($chunk->all());

方法2

 // Slice the collection to get the items to display in current page
 $currentPageItems = $collection->slice(($pageNumber * $numberOfItemsPerPage) - $numberOfItemsPerPage, $numberOfItemsPerPage)->all();

 // Create the paginator and use
 $chunk = new LengthAwarePaginator($currentPageItems , count($collection), $numberOfItemsPerPage);

 dd($chunk);