问题:
使用 Laravel 执行原始 MySQL 查询,包括复杂的 UNION操作,导致“未定义的属性”错误。
查询:
<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() 等操作使用方法链。但是,构建器格式不支持 UNION 操作,必须通过 DB::select() 手动执行。
以上是如何修复 Laravel 5.1 使用 UNION 执行原始查询时出现的'未定义属性”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!