所以我有一个小查询要在我的数据库上运行,它在MySQL Workbench中运行得很好。基本上,一个带左连接的SELECT和带左连接的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
他试图把它翻译成拉腊维尔语,但没有成功。
$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行出现错误异常:未定义的属性:照明\数据库\口才\生成器::$绑定
如何在Laravel中执行一个完全原始的查询,或者如何在Laravel中以正确的方式编写查询?
5条答案
按热度按时间js5cn81o1#
我在this topic中找到了解决方案,并编写了以下代码:
iyfamqjs2#
我在迁移中使用它向列添加索引
oknwwptz3#
Laravel文件中的示例:
另一个例子:
另一个例子-我们甚至可以在同一条语句中执行avg()和count()。
学分:https://blog.quickadminpanel.com/5-ways-to-use-raw-database-queries-in-laravel/
hfsqlsce4#
此外,您还可以使用
fnvucqvd5#
你也可以像这样运行原始查询。