samyak tuladhar
samyak tuladhar

Reputation: 11

how to get random data along with groupby from relations?

I have vehicles table that has relation with vehicle_Model and vehicle vehicle_vendor table.

Now I want to generate only 3 random rows/tuple each time page refreshes.

I have already tried this but when using ->groupBy() it does not generate random data.

$models = VehicleModel::has('vehicle')->inRandomOrder()->pluck('id')->take(3);

return Vehicle::has('vehicleModel')->has('vehicleModel.vehicleVendor')->whereIn('vehicle_model_id',$models)->with(['vehicleModel','vehicleModel.vehicleVendor'])->inRandomOrder()->take(3)->groupBy(['vehicle_model_id',])->get()->pluck('id');

Upvotes: 0

Views: 256

Answers (2)

samyak tuladhar
samyak tuladhar

Reputation: 11

found the solution instead of using group by looping through the vehicle_model_id works

$vehicles = [];

foreach($models as $model){

$vehicles = Vehicle::where('vehicle_model_id',$model)->with(['vehicleModel','vehicleModel.vehicleVendor'])->inRandomOrder()->first();
}

Upvotes: 0

thisiskelvin
thisiskelvin

Reputation: 4202

You may have your ->pluck('id') and ->take(3) in the wrong order. You are also not using ->get() to complete your query.

->pluck() is a collection method used after completing the eloquent query once a collection object is returned. To select what fields you would like to get before completing the query you should be able to use ->select().

However, to solve your issue:

$models = VehicleModel::has('vehicle')
    ->inRandomOrder()
    ->take(3)
    ->get()
    ->pluck('id')
    ->all();

This should return an array with 3 random model ids to use in your other query. ->all() is used to convert the collection object into an array.

From here, you need to remove your ->whereIn() as it is checking against the Vehicle and not the VehicleModel. You can extend the ->with() call like so:

...

->with(['vehicleModel' => function ($query) use ($models) {
    $query->whereIn('id', $models);
}, 'vehicleModel.vehicleVendor'])

...

This will only add vehicle models which have an id contained in the $models array.

I hope this helps.

Upvotes: 1

Related Questions