gpt4 book ai didi

php - 如何使用 Laravel 5.1 执行原始查询?

转载 作者:行者123 更新时间:2023-11-30 22:11:38 26 4
gpt4 key购买 nike

所以我在我的数据库上运行了这个小查询,它在 MySQL Workbench 中运行良好。基本上,一个带有 LEFT JOIN 的 SELECT 和一个带有 LEFT JOIN 的 UNION。

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 in Builder.php line 1249: Undefined property: Illuminate\Database\Eloquent\Builder::$bindings

我如何在 Laravel 中执行完全原始的查询或在 Laravel 中以正确的方式编写查询?

最佳答案

我在 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");

关于php - 如何使用 Laravel 5.1 执行原始查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com