Laravel - Union + Paginate at the same time? and another problem----1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from


 

###

這是這幾天,碰到的一個比較頭疼的問題

使用union all聯合查詢,同時laravel 生成分頁,但發生報錯?

QueryException in Connection.php line 729:
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from (select * from `orders` where (`status` = completed and `refund_status` in (refunded, not_apply)) or `refund_status` = refunded) as orders left join `users` on `users`.`id` = `orders`.`user_id` left join `order_products` on `order_products`.`order_id` = `orders`.`id` where exists (select 1 from `order_products` where exists (select 1 from `products` where products.id = order_products.product_id) and order_products.order_id = orders.id) and exists (select ....

 

 

###

 

 由於使用聯合查詢跟使用paginate()來生成分頁,導致此問題,解決方法是,先獲取到數據,就先不用直接調用分頁函數,然后在進行分頁處理就可以

 

在stackoverflow ,找到的問題解決方式

https://stackoverflow.com/questions/25338456/laravel-union-paginate-at-the-same-time

 

使用這個方法處理 https://laracasts.com/discuss/channels/general-discussion/paginator-class-is-missing

 

在我決解過程中,會需要引入相關到類

use Illuminate\Support\Facades\Input;
use Illuminate\Pagination\LengthAwarePaginator;

 

       // 處理分頁問題
        $page = Input::get('page', 1);
       // Number of items per page
       perPage = 5;
       // Start displaying items from this number;
       $offSet = ($page * $perPage) - $perPage; 
       // Get only the items you need using array_slice (only get 10 items since that's what you need)
       $itemsForCurrentPage = array_slice($report_infos, $offSet, $perPage, true);
        // Return the paginator with only 10 items but with the count of all items and set the it on the correct page
       $report_infos = new LengthAwarePaginator($itemsForCurrentPage, count($report_infos), $perPage, $page, ['path' => request()->url(), 'query' => request()->query()]);
注意⚠️:當我們需要跳轉頁面當時候,有時我們是還有其他參數當,所以需要傳入當前url,跟查詢參數
['path' => request()->url(), 'query' => request()->query()]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM