嗨,我对Laravel中的DB raw有疑问。实际上,现在我有一个名为$currencies
的变量,其结构如下。
<?php
$currencies = [
'CNY' => 1000,
'USD' => 10000
]
我需要使用该数组的值对我的产品表进行排序。 products
表如下所示:
| id | product_name | original_currency | price |
| 1 | lorem ipsum d | CNY | 20 |
| 2 | new product n | USD | 10 |
到目前为止,我的代码如下:
$products = DB::raw(SELECT product_name,
price,
price * $currencies[original_currency] AS converted_price
FROM products);
但是我收到了错误Undefined Index: original_currency
我只需要访问正确的值即可设置converted_price
。因此,预期结果将如下所示:
| id | product_name | original_currency | price | converted_price |
| 1 | lorem ipsum d | CNY | 20 | 20000 |
| 2 | new product n | USD | 10 | 1000000 |
答案 0 :(得分:1)
问题:
解决方案:
方法1:从MySQL获取简单数据,然后在PHP中修改数据
$products = DB::raw('SELECT products.product_id, products.original_currency, products.price FROM products);
foreach($products as $key => $value) {
$value['converted_price'] = $value['price'] * $currencies[$value['original_currency']];
}
方法2:在MySQL中使用Temp表:
SELECT
products.product_id,
products.price,
products.price * weight_table.weight AS converted_price
FROM products
INNER JOIN (
SELECT 'CNY' AS currency, 100 AS weight
UNION
SELECT 'USD' AS currency, 1000 AS weight
) AS weight_table
ON products.original_currency = weight_table.currency;
如果您在PHP中具有动态货币数组,请使用以下代码生成内部临时表。
$currencies = [
'CNY' => 100,
'USD' => 1000
];
function getTempTable($arrCurrency) {
$arrQuery = [];
foreach($arrCurrency as $key => $value) {
$arrQuery[] = "SELECT '" . $key . "' AS currency, " . $value . " AS weight";
}
return implode(PHP_EOL. " UNION " . PHP_EOL, $arrQuery);
}
$strQuery = 'SELECT
products.product_id,
products.price,
products.price * weight_table.weight AS converted_price
FROM products
INNER JOIN ( ' . getTempTable($currencies) . ') AS weight_table
ON products.original_currency = weight_table.currency';
$products = DB::raw($strQuery);