【问题标题】:How can I convert this query to a laravel syntax to use pagination如何将此查询转换为 laravel 语法以使用分页
【发布时间】:2019-02-03 16:11:25
【问题描述】:
$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()

【问题讨论】:

标签: php sql laravel


【解决方案1】:

假设您已经设置了 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);

【讨论】:

    【解决方案2】:

    好吧,因为你既没有使用 Eloquent 也没有使用 Query builder,你将不得不做一些额外的工作来享受 paginate() 的强大功能。

    使用 Laravel 的原始查询支持,试试这个:

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

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

    方法一

    $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      相关资源
      最近更新 更多