如何在DB Raw Laravel中使用数组的值

时间:2019-08-26 09:19:47

标签: php mysql laravel laravel-5

嗨,我对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          |

1 个答案:

答案 0 :(得分:1)

问题:

  • 将查询作为字符串传递,查询中缺少单引号或双引号。
  • 您不能在查询中直接使用PHP数组,因为查询已发送到MySQL服务器,并且无法访问您的PHP变量。

解决方案:

方法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);