Przemek
Przemek

Reputation: 822

laravel eloquent merge 2 queries before executing them?

I have 2 queries like this:

$expiresAt = Carbon::now()->addMinutes(10);
$thumbnails = Cache::remember('entities-thumbnails-'.$entity_id, $expiresAt, function () use ($entity_id) {
    return Images::where(['entity_id' => $entity_id, 'image_style' => 'thumbnail'])
        ->select('path AS thumbnail', 'width As thumbnailWidth', 'height As thumbnailHeight');
});
$largeImages = Cache::remember('entities-largeImages-'.$entity_id, $expiresAt, function () use ($entity_id) {
    return Images::where(['entity_id' => $entity_id, 'image_style' => 'large'])
        ->select('path AS src')
        ->union($thumbnails)
        ->get();
});

What I want to do is not execute them seperately but as one query. Overall there will be 4 queries therefore instead of doing 4 I want to do one, is that possible? How does union work exactly?

Upvotes: 0

Views: 190

Answers (1)

Chay22
Chay22

Reputation: 2894

Storing whole plain results in PHP variable then let PHP do such filtering would be better in my point of view. As an example

$images = Image::where('entity_id', $entity_id)->get();

$thumbnails = Cache::remember('entities-thumbnails-'.$entity_id, $expiresAt, function () use ($images) {
    return $images->filter(function ($image) {
        return $image->image_style === 'thumbnail';
    });
});

$largeImages = Cache::remember('entities-largeImages-'.$entity_id, $expiresAt, function () use ($images) {
    return $images->filter(function ($image) {
        return $image->image_style === 'large';
    });
});

You might call UNION is literally the same as JOIN. But, it does combining results set into one in an operation rather than relate them horizontally. Still, both need to be separated by PHP, as each row recorded are united into one collection.

I'm assuming you still need to make aliases for specified columns. Fortunately, Laravel is able to do that out of the box.

$thumbnails = Cache::remember('entities-thumbnails-'.$entity_id, $expiresAt, function () use ($images) {
    return $images->filter(function ($image) {
        if ($image->image_style === 'thumbnail') {
            $image->setAttribute('thumbnail', $image->path);  
            $image->setAttribute('thumbnailWidth', $image->width); 
            $image->setAttribute('thumbnailHeight', $image->height);                

            return true;
        }

        return false;
    });
});

$largeImages = Cache::remember('entities-largeImages-'.$entity_id, $expiresAt, function () use ($images) {
    return $images->filter(function ($image) {
        if ($image->image_style === 'large') {
            $image->setAttribute('src', $image->path);  

            return true;
        }

        return false;
    });
});

Upvotes: 1

Related Questions