問題:
使用Laravel 來執行原始複雜的UNSQL操作,導致“未定義的屬性”錯誤。
查詢:
<code class="mysql">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</code>
Laravel 嘗試失敗:
<code class="php">$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();</code>
解決方案:
使用DB::select() 直接對資料庫執行查詢。
<code class="php">$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");</code>
「未定義屬性」的原因" 錯誤:
Laravel 的selectRaw() 方法期望查詢採用Eloquent 建構器格式,這涉及對leftJoin( ) 和whereNotIn() 等操作使用方法鏈。
以上是如何修復 Laravel 5.1 使用 UNION 執行原始查詢時出現的「未定義屬性」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!