@oroalej please provide a code for more clarification..
Union with pagination - Laravel 5.6
Hi Guys,
How can I add pagination on a union. I got an error Cardinality Violationwhen using union with ->paginate().
@biishmar Everything is working fine when I didn't use ->paginate(), but when I do, the error appear. It seems like paginate is not working with union. Is there any work around?
@oroalej would you please show that code? paginate only works for query builder, i think u calling paginate from collection.
@biishmar Its because your queries have different selects. Try use ->select() same fields in both queries and run paginate. This should help
@Agelios i aint the one asked this question
@Agelios I tried adding select to both queries, but it only works when I select 1 column. When I select 2 or more columns, the error showed up again.
@biishmar Like I said, it is working fine if I remove the ->union() code.
Sample code:
$first = Model::SomeConditions;
$second = Model::SomeConditions
->union($first) <<<--- If i remove this, everything is working fine.
->paginate(5);
$first = I'm trying to get only the featured professional where featured_date >= today.
$second = I'm trying to get the latest professional and combining the result with $first.
@oroalej Need full code.
$first = DB::table('sometable')->select('firstcolumn', 'secondcolumn')->where('somethink', $somethink);
$second = DB::table('other_table')->select('same_column_as_first, ..')->where(cond)->union($first)->paginate();
its work fine
@oroalej i dont know the solution for the current problem, if u want pagination that badly u have to create manually..
check this link https://laravel.com/docs/5.6/pagination#manually-creating-a-paginator
seems like union doesnt cooperate with paginate.
Here is the code
$featuredProfessionals = Professional::select('name', 'id')
->WhereNotNull('matterport_url')
->where('name', 'LIKE', "%{$search}%")
->where('featured_ends_at', '>=', now());
$professionals = Professional::select('name', 'id')
->WhereNotNull('matterport_url')
->where('name', 'LIKE', "%{$search}%")
->union($featuredProfessionals)
->latest()
->paginate(5);
You need to use the length aware paginator (custom) see here: https://laracasts.com/discuss/channels/tips/length-aware-paginator
Another article and case stydy: https://christophersax.com/2016/custom-lengthawarepaginator-in-laravel/
Please or to participate in this conversation.