I am pulling two different data from the same table in the database.I'm merging this data with union but not all results are shown. So I want to use unionAll. Can I use it with Eloquent?
My code:
$model = OrderDetail::with('product')->whereBetween('created_at', [Carbon::createFromDate($request['year_first'])->startOfYear(), Carbon::createFromDate($request['year_first'])->endOfYear()])->get()->groupBy(['service_id'])
->union(OrderDetail::with('product')->whereBetween('created_at', [Carbon::createFromDate($request['year_last'])->startOfYear(), Carbon::createFromDate($request['year_last'])->endOfYear()])->get()->groupBy(['service_id']));
When I try with unionAll() I get the following error:
Method Illuminate\Database\Eloquent\Collection::unionAll does not exist.
Does unionAll() have different uses?
Your query uses union
from the collection not the union
of the query builder. This is because you have a get()
before the union
. To get a rather similar (but probably not identical) result to what you need you can do:
$model = OrderDetail::with('product')->whereBetween('created_at', [Carbon::createFromDate($request['year_first'])->startOfYear(), Carbon::createFromDate($request['year_first'])->endOfYear()])
->unionAll(OrderDetail::with('product')->whereBetween('created_at', [Carbon::createFromDate($request['year_last'])->startOfYear(), Carbon::createFromDate($request['year_last'])->endOfYear()]))
->get()->groupBy(['service_id']);
This makes union
and unionAll
usable in that part of the query. Sidenote you might have issues with the eager loading, I've not checked if it can happen in a union query.