为了账号安全,请及时绑定邮箱和手机立即绑定

php 到 laravel 中的隐蔽条件查询

php 到 laravel 中的隐蔽条件查询

PHP
慕桂英4014372 2023-10-15 15:09:12
我正在尝试将一些 php 代码更改为 laravel,但这是需要更新的一些条件,我如何在 laravel 中实现它们?我只想写更新方法来更新但是我怎样才能实现这个条件这是一些我想转换为 laravel 的 php 查询UPDATE products SET name="new Product" WHERE price=40 AND status=0UPDATE products SET name="old one" WHERE price=100UPDATE products SET price=0 WHERE status=2
查看完整描述

2 回答

?
桃花长相依

TA贡献1860条经验 获得超8个赞

首先使用在您的应用程序中创建一个模型


php artisan make:model Product

那么您所要做的就是使用该模型来查询结果:


//add Product model namespace on the top

use App\Product;



Product::where('price', 40)->where('status', 0)

                           ->update(['name' => 'new Product']);


Product::where('price', 100)

        ->update(['name' => 'old one']);


Product::where('price', 0)

        ->update(['status' => 2]);

您可以根据需要放置任意多个 where 子句,并且可以将任何数组传递给 update 方法。只需根据需要更新数组


,如果您希望它们同时运行:


use DB;

use App\Product;

use Exception;

public function update()

{

    DB::beginTransaction();

    try {

        Product::where('price', 40)->where('status', 0)

            ->update(['name' => 'new Product']);


        Product::where('price', 100)

            ->update(['name' => 'old one']);


        Product::where('price', 0)

            ->update(['status' => 2]);

        $status = true;

    } catch (Exception $exception) {

        $status = false;

    }


    if ($status) {

        DB::commit();

    } else {

        DB::rollBack();

    }

}

或者您可以编写一行代码使其动态化:


   $conditions = [

        ['price', 40],

        ['status', 0]

    ];

    

    $data = ['name' => 'new name'];

    

    Product::where($conditions)->update($data);


查看完整回答
反对 回复 2023-10-15
?
子衿沉夜

TA贡献1828条经验 获得超3个赞

使用数据库查询来更新您的数据。


DB::table('products')->where('price', 40)->where('status', 0)->update(['name' => 'new Product']);


DB::table('products')->where('price', 100)->update(['name' => 'old one']);


DB::table('products')->where('price', 0)->update(['status' => 2]);

或者如果您想使用模型更新数据,则使用


Use App\Product;代码顶部


Use App\Product;


Product::where('price', 40)->where('status', 0)->update(['name' => 'new Product']);


Product::where('price', 100)->update(['name' => 'old one']);


Product::where('price', 0)->update(['status' => 2]);


查看完整回答
反对 回复 2023-10-15
  • 2 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信