[英]Laravel: How Can I Convert This Sql Statement to Eloquent or Query Builder
[英]Laravel: How Can I Convert This Sql Statement to Eloquent or Query Builder?
我需要將不同貨幣的產品價格轉換為美元。 我有兩張桌子:產品和貨幣。
| id | currency | value_usd |
+----+----------+-----------+
| 1 | USD | 1 |
| 2 | AUD | 1.077315 |
| 3 | GBP | 0.620868 |
| 4 | EUR | 0.775338 |
+----+----------+-----------+
+----+-------------+----------+
| id | price | currency |
+----+-------------+----------+
| 1 | 100 | USD |
| 2 | 50 | GBP |
| 3 | 75 | EUR |
| 4 | 60 | GBP |
+----+-------------+----------+
我在Laravel的第二次JOIN遇到了麻煩
SELECT
p.slug,
p.price,
p.currency,
price * (c2.value_usd * c1.value_usd) as converted_price,
c2.currency as converted_currency
FROM `products` p
JOIN `currencies` c1 ON p.currency = c1.currency
JOIN `currencies` c2 ON c2.currency = 'USD'
我試過這個
$query = \DB::table('products')
->join('currencies AS c1', 'products.currency', '=', 'c1.currency')
->join('currencies AS c2', 'c2.currency', '=', 'USD')
->get();
但是得到了錯誤
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'USD' in 'on clause' (SQL: select * from `products` inner join `currencies` as `c1` on `products`.`currency` = `c1`.`currency` inner join `currencies` as `c2` on `c2`.`currency` = `USD`)
把這個DB::raw("('USD')")
放在join中
$query = \DB::table('products')
->join('currencies AS c1', 'products.currency', '=', 'c1.currency')
->join('currencies AS c2', 'c2.currency', '=', DB::raw("('USD')"))
->get();
希望它會奏效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.