如何在laravel中使用Union和Paginate

时间:2018-06-09 18:19:55

标签: laravel pagination eloquent union

我希望联合两个模型和分页结果但得到错误,在贝娄看到我的电话代码和结果:

$this->archive = $this->archive
        ->select (['id','property_id','plan_id','pay_id','price','period','start_at','expire_at'])
        ->whereHas('property',function ($query) use ($user){
        $query->select(['user_id','type_id','title'])->where('user_id',$user);
        })->with(['property'=>function($query){
            $query->select('title','id');
        },'property.owner'=>function($query){
            $query->select('name','family','id');
        },'plan'=>function($query){
            $query->select('title','price','id','status');
        },'transaction'=>function($query){
            $query->select('port','price','id','status','payment_date');
        }]);
    $this->model = $this->model
        ->select (['id', 'property_id','plan_id','pay_id','price','period','start_at','expire_at'])
        ->whereHas('property',function ($query) use ($user){
        $query->select(['user_id','type_id','title'])->where('user_id',$user);
        })->with(['property'=>function($query){
            $query->select('title','id');
        },'property.owner'=>function($query){
            $query->select('name','family','id');
        },'plan'=>function($query){
            $query->select('title','price','id','status');
        },'transaction'=>function($query){
            $query->select('port','price','id','status','payment_date');
        }])
        ->union($this->archive)->orderBy('expire_at','DESC')->paginate ($paginate);

他们的结果是:

SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns

请帮帮我

2 个答案:

答案 0 :(得分:0)

与Laravel中的not supported分页是因为没有优雅的方法可以做到没有重大缺点。

答案 1 :(得分:0)

你可以像这样结合sql结果,

$result = $query1->merge($query2);

        $resultSorted = $result->sortByDesc('expire_at');

        $count = $query1->count() + $query2->count();
        $page = $request['page'];
        $perPage = 20;

        $resultSorted = new LengthAwarePaginator(
            $resultSorted->forPage($page, $perPage), $count, $perPage, $page
        );