所以我在我的数据库上运行这个小查询,它在MySQL Workbench中工作正常。 基本上,SELECT LEFT JOIN和UNION再次LEFT JOIN。
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();
我收到了错误
Builder.php第1249行中的ErrorException:未定义属性: 照亮\数据库\雄辩\生成器:: $绑定
如何在Laravel中执行完全原始查询或在Laravel中以正确的方式编写查询?
答案 0 :(得分:104)
我在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 :(得分:1)
DB::statement("your query")
我用它为迁移中的列添加索引
答案 2 :(得分:-3)
您也可以以这种方式运行原始查询。
DB::table('setting_colleges')->first();