I was unable to achieve the desired result with just one query - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Sunday, September 24, 2023

I was unable to achieve the desired result with just one query

I'm using Laravel Eloquent to grab some videos in a certain order.

Is it possible to achieve the same result with just one query?

Random order is not necessary.

Maybe retrieve the videos in the specified order(Cars, Bikes, Trucks) with a single query.

protected function related(Video $video): Collection
    {
        $nVideos = 6;

        $carVideos = Video::whereNot('id', $video->id)
            ->whereHas('cars', function (Builder $q) use ($video) {
                $q->whereIn('id', $video->cars->pluck('id')->toArray());
            })
            ->inRandomOrder()
            ->take($nVideos)
            ->get();

        if ($carVideos->count() >= $nVideos) {
            return $carVideos;
        }

        $bikeVideos = Video::whereNot('id', $video->id)
            ->whereHas('bikes', function (Builder $q) use ($video) {
                $q->whereIn('id', $video->bikes->pluck('id')->toArray());
            })
            ->inRandomOrder()
            ->take($nVideos)
            ->get();

        $merged = $carVideos->merge($bikeVideos);

        if ($merged->count() >= $nVideos) {
            return $merged;
        }

        $truckVideos = Video::whereNot('id', $video->id)
            ->whereHas('trucks', function (Builder $q) use ($video) {
                $q->whereIn('id', $video->trucks->pluck('id')->toArray());
            })
            ->inRandomOrder()
            ->take($nVideos)
            ->get();

        return $merged->merge($truckVideos);
    }


source https://stackoverflow.com/questions/77162686/i-was-unable-to-achieve-the-desired-result-with-just-one-query

No comments:

Post a Comment