Reputation: 63
I Want To Union two Model And Paginate Result But Get Error, In Bellow See My Call Code And Result:
$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);
And Result Of Them Is:
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns
Please Help Me
Upvotes: 0
Views: 1595
Reputation: 480
you can union sql results like this,
$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
);
Upvotes: 1
Reputation: 9952
Pagination with union is not supported in Laravel since there's no elegant way to do it without major drawbacks.
Upvotes: 0