laravel eloquent在执行之前合并2个查询?

时间:2017-11-28 09:53:59

标签: laravel laravel-5 eloquent

我有2个这样的查询:

$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();
});

我想要做的不是单独执行它们,而是作为一个查询。总的来说会有4个查询因此而不是4个我想做一个,这可能吗?工会如何正常工作?

1 个答案:

答案 0 :(得分:1)

将整个普通结果存储在PHP变量中然后让PHP进行此类过滤在我看来会更好。作为一个例子

$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';
    });
});

您可以致电UNIONJOIN完全相同。但是,它确实将结果集合在一个操作中,而不是将它们水平关联。但是,两者都需要用PHP分隔,因为记录的每一行都合并为一个collection

我假设你仍然需要为指定的列创建别名。幸运的是,Laravel能够开箱即用。

$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;
    });
});