Rumah >pangkalan data >tutorial mysql >Bagaimana untuk Membetulkan Ralat \'Undefined property\' dalam Laravel 5.1 Apabila Melaksanakan Pertanyaan Mentah dengan UNION?
Masalah:
Melaksanakan pertanyaan MySQL mentah dengan Laravel, termasuk UNION yang kompleks operasi, mengakibatkan ralat "Harta tidak ditentukan".
Pertanyaan:
<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>
Percubaan Laravel yang Gagal:
<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>
Penyelesaian:
Laksanakan pertanyaan secara langsung terhadap pangkalan data menggunakan 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>
Sebab untuk "Undefined property " Ralat:
Kaedah selectRaw() Laravel menjangkakan pertanyaan berada dalam format pembina Eloquent, yang melibatkan penggunaan kaedah rantaian untuk operasi seperti leftJoin() dan whereNotIn(). Walau bagaimanapun, operasi UNION tidak disokong dalam format pembina dan mesti dilaksanakan secara manual melalui DB::select().
Atas ialah kandungan terperinci Bagaimana untuk Membetulkan Ralat \'Undefined property\' dalam Laravel 5.1 Apabila Melaksanakan Pertanyaan Mentah dengan UNION?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!