I need to convert products price with different currencies to USD. I have two tables: products and currencies.
| 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 |
+----+-------------+----------+
I have troubles with second JOIN in Laravel
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'
I tried this
$query = \DB::table('products')
->join('currencies AS c1', 'products.currency', '=', 'c1.currency')
->join('currencies AS c2', 'c2.currency', '=', 'USD')
->get();
but got error
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`)
put this DB::raw("('USD')")
in join
$query = \DB::table('products')
->join('currencies AS c1', 'products.currency', '=', 'c1.currency')
->join('currencies AS c2', 'c2.currency', '=', DB::raw("('USD')"))
->get();
hope it will work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.