2017-11-28 13 views
0

私はこのような2つのクエリを持っている:laravel 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(); 
}); 

私は別々が、1つのクエリとしてそれらを実行されていませんやりたいです。全体的に4つのクエリがあるので、代わりに4つのクエリがあります。私は1つを実行したい、それは可能ですか?組合はどのようにして正確に働くのですか?

答えて

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'; 
    }); 
}); 
例として、あなたは UNIONは文字通り JOINと同じであると呼ぶかもしれません。しかし、結果を水平に関連付けるのではなく、操作の中で1つにまとめることができます。それでも、記録された各行は1つの collectionに統合されているため、PHPで区切る必要があります。

指定した列に別名を付ける必要があるとします。幸いにも、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; 
    }); 
}); 
+0

非常に良い説明です。私はララベルの雄弁にこのようなオプションがあることを知らなかった、私は間違いなく私の質問のほとんどのためにこれを再利用します。ありがとう! – Przemek

関連する問題