2017-08-04 31 views
0

我有以下查詢:Laravel 5.2 - 奇怪的結果當使用左連接的子查詢

$products = Product::leftJoin(DB::Raw('(SELECT imageable_id, MIN(created_at) as min_created_at 
           FROM images WHERE imageable_type = "App\\\Product" 
           GROUP BY imageable_id) AS subquery'), function($join) { 
           $join->on('subquery.imageable_id', '=', 'products.id'); 
         }) 
         ->leftJoin('images', function ($join) { 
          $join->on('images.imageable_id', '=', 'subquery.imageable_id') 
           ->where('images.created_at', '=', 'subquery.min_created_at');}) 
         ->select('products.*', 'images.file_path') 
         ->paginate(5); 

當我死了和轉儲查詢日誌,上面被翻譯如下:

"query" => """ 
    select `products`.*, `images`.`file_path` from `products` 
    left join (SELECT imageable_id, MIN(created_at) as min_created_at 
       FROM images WHERE imageable_type = "App\\Product" 
       GROUP BY imageable_id) AS subquery on `subquery`.`imageable_id` = `products`.`id` 
    left join `images` on `images`.`imageable_id` = `subquery`.`imageable_id` and `images`.`created_at` = ? 
    limit 5 offset 0 
    """ 
"bindings" => array:1 [ 
     0 => "subquery.min_created_at" 

] 

這看起來是正確的,但我不確定爲什麼綁定已被添加爲subquery.min_created_at

現在,當我執行上述查詢laravel imagesfile_path總是空,當我清楚我知道有相關的圖像。當我通過粘貼它並在MySQL命令行中直接運行來測試上述查詢時,我會得到預期的結果,即對於具有圖像的產品,image_file的file_path不爲空。當我在MySQL命令行中運行時,唯一的區別是我沒有對subquery.min_created_at進行任何綁定 - 我只是替換了?與subquery.min_created_at

任何想法爲什麼查詢的行爲是這樣的。如果我刪除第二個左連接是否能夠正常工作,但後來我不能選擇創建的第一個圖像加載例如做以下給我FILE_PATH:

$products = Product::leftJoin(DB::Raw('(SELECT imageable_id, file_path 
           FROM images WHERE imageable_type = "App\\\Product" 
           GROUP BY imageable_id) AS subquery'), function($join) { 
           $join->on('subquery.imageable_id', '=', 'products.id'); 
         }) 
         ->select('products.*', 'subquery.file_path') 
         ->paginate(5); 

理想我想我原來的查詢中工作 - 任何幫助讚賞。

+0

' - >在哪裏( 'images.created_at', '=', 'subquery.min_created_at')' - 你需要使用'DB ::原始()'第二個參數。 –

+0

或使用' - > on()' –

回答

1

您正在使用->where()你的第二個連接條件:

->where('images.created_at', '=', 'subquery.min_created_at') 

這產生

and `images`.`created_at` = ? 

其結合是。

相反,你應該使用->on();

$join->on('images.imageable_id', '=', 'subquery.imageable_id') 
    ->on('images.created_at', '=', 'subquery.min_created_at');