如何在Laravel,子查询中进行更新

时间:2017-11-04 13:06:58

标签: php laravel laravel-5 subquery

如何在Laravel 5.2中进行此查询:

UPDATE product p
    SET price = ( SELECT price FROM product_price WHERE product_id = p.id AND price > 0 AND inventory > 0 AND active = 1 ORDER BY price desc limit 1)
    SET discounts = ( SELECT discount FROM product_price WHERE product_id = p.id AND price > 0 AND inventory > 0 AND active = 1 ORDER BY price desc limit 1)
    WHERE
    product_state = 1

如何用db运行它?

2 个答案:

答案 0 :(得分:0)

您可以为这种复杂查询应用原始表达式。以下是官方Laravel Doc上的示例参考:

https://laravel.com/docs/5.5/queries#raw-expressions

答案 1 :(得分:0)

我们需要查看您确切的数据库架构和一些数据,以确认,但以下内容应该在正确的轨道上:

use DB; // Ensure we have access to the DB facade

$result = DB::table('product')
    ->where('product_state', '=', 1)
    ->update([
        'price'     => DB::raw('(SELECT price FROM product_price WHERE product_id = product.id AND price > 0 AND inventory > 0 AND active = 1 ORDER BY price desc limit 1)'),
        'discounts' => DB::raw('(SELECT discount FROM product_price WHERE product_id = product.id AND price > 0 AND inventory > 0 AND active = 1 ORDER BY price desc limit 1)')
    ]);