mysql - 拉拉维尔 : How Can I Convert This Sql Statement to Eloquent or Query Builder?

标签 mysql laravel-5

我需要将不同货币的产品价格转换为美元。我有两个表:产品和货币。

| 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')") 在加入

$query = \DB::table('products')
          ->join('currencies AS c1', 'products.currency', '=', 'c1.currency')
          ->join('currencies AS c2', 'c2.currency', '=', DB::raw("('USD')"))      
          ->get();

希望能成功

关于mysql - 拉拉维尔 : How Can I Convert This Sql Statement to Eloquent or Query Builder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55357783/

相关文章:

mysql - 如何将 AUTO_INCRMENT 添加到现有列?

mysql - 如何自动化地将密码安全地传递给 MySQL 客户端

php - Laravel getCountForPagination() 返回 Object 而不是 int

database - Laravel 5 为测试之间的单元测试重新播种数据库

php - Laravel 调度程序时区

laravel - 如何创建仅用于测试的 Laravel 路由(phpunit)?

php - Laravel 意外重定向 ( 302 )

php - 从数据库中删除表后,学说显示 'MappingException' 。 [交响乐]

c++ - sql Column with multiple values(cpp文件中的查询实现)

mysql - 组合选择查询