Andreu Ramos
Andreu Ramos

Reputation: 2908

Ordering by related to table in Laravel

I have a model (vehicle) related to other 2 models (car & bike). A car belongsTo a Vehicle as well as a bike. A vehicle hasOne car OR hasOne bike.

I want to sort all my vehicles randomly and first the bikes and then the cars. I mean first all the cars ordered randomly and then all the bikes ordered randomly.

I must do this in a paginate way, so it must be done in a single query.

The approximations I've done are the following: order by car_id (then the bikes come first) but the order is always the same, I need to add the random factor inside each group.

Any tip will help. Thanks!

Upvotes: 1

Views: 84

Answers (1)

Limon Monte
Limon Monte

Reputation: 54389

Union should work:

$cars = Vehicle::selectRaw('*, 1 as ob')->whereNotNull('car_id');
$bikes = Vehicle::selectRaw('*, 2 as ob')->whereNotNull('bike_id');

$vehicles = $cars->union($bikes)->orderByRaw('ob, RAND()')->paginate(10);

Read more about order when using union.

Upvotes: 1

Related Questions