2015-10-10 80 views
23

所以我有這個小小的查詢在我的數據庫上運行,它在MySQL Workbench中工作正常。 基本上,一個選擇與左聯接和聯合與左聯接再次。如何使用Laravel 5.1執行原始查詢?

SELECT 
    cards.id_card, 
    cards.hash_card, 
    cards.`table`, 
    users.name, 
    0 as total, 
    cards.card_status, 
    cards.created_at 
FROM cards 
LEFT JOIN users 
ON users.id_user = cards.id_user 
WHERE hash_card NOT IN (SELECT orders.hash_card FROM orders) 
UNION 
SELECT 
    cards.id_card, 
    orders.hash_card, 
    cards.`table`, 
    users.name, 
    sum(orders.quantity*orders.product_price) as total, 
    cards.card_status, 
    max(orders.created_at) 
FROM menu.orders 
LEFT JOIN cards 
ON cards.hash_card = orders.hash_card 
LEFT JOIN users 
ON users.id_user = cards.id_user 
GROUP BY hash_card 
ORDER BY id_card ASC 

在試圖將它翻譯成Laravel,沒有成功。

$cards = Card::selectRaw('cards.id_card, cards.hash_card ,cards.table, users.name, 0 as total, cards.card_status, cards.created_at as last_update') 
       ->leftJoin('users','users.id_user','=','cards.id_user') 
       ->whereNotIn('hash_card', Order::select('orders.hash_card')->get()) 
       ->union(
         Order::selectRaw('cards.id_card, orders.hash_card, cards.table, users.name, sum(orders.quantity*orders.product_price) as total, cards.card_status, max(orders.created_at) as last_update') 
         ->leftJoin('cards','cards.hash_card','=','orders.hash_card') 
         ->leftJoin('users','users.id_user','=','cards.id_user') 
       ) 
       ->groupBy('hash_card') 
       ->orderBy('cards.id_card','asc') 
       ->get(); 

,我發現了錯誤

ErrorException在Builder.php線1249:未定義的屬性: 照亮\數據庫\雄辯\生成器:: $綁定

怎麼可能我在Laravel中執行完全原始的查詢或在Laravel中以正確的方式編寫查詢?

回答

53

我找到了解決方案this topic和我的代碼如下:

$cards = DB::select("SELECT 
           cards.id_card, 
           cards.hash_card, 
           cards.`table`, 
           users.name, 
           0 as total, 
           cards.card_status, 
           cards.created_at as last_update 
          FROM cards 
          LEFT JOIN users 
          ON users.id_user = cards.id_user 
          WHERE hash_card NOT IN (SELECT orders.hash_card FROM orders) 
          UNION 
          SELECT 
           cards.id_card, 
           orders.hash_card, 
           cards.`table`, 
           users.name, 
           sum(orders.quantity*orders.product_price) as total, 
           cards.card_status, 
           max(orders.created_at) last_update 
          FROM menu.orders 
          LEFT JOIN cards 
          ON cards.hash_card = orders.hash_card 
          LEFT JOIN users 
          ON users.id_user = cards.id_user 
          GROUP BY hash_card 
          ORDER BY id_card ASC"); 
+1

你其實並不甚至需要嵌套DB ::原始通話。你可以調用DB :: select(「...你的查詢字符串...」); –

+0

你是對的!我刪除了嵌套數據庫:原始,它的作品就像一個魅力! ;) –

+2

我有一個問題,如果我可以。在Laravel 5中使用查詢構建器(帶或不帶DB :: raw)使用原始sql查詢是否足以防止sql注入?我找到了一些關於它的文章,但它是用於Laravel 4.我找不到一個令人信服的確認。 – Robert