php 到 laravel 中的隐蔽条件查询

我正在尝试将一些 php 代码更改为 laravel,但这是需要更新的一些条件,我如何在 laravel 中实现它们?我只想写更新方法来更新但是我怎样才能实现这个条件


这是一些我想转换为 laravel 的 php 查询


UPDATE products SET name="new Product" WHERE price=40 AND status=0


UPDATE products SET name="old one" WHERE price=100


UPDATE products SET price=0 WHERE status=2


慕桂英4014372
浏览 67回答 2
2回答

桃花长相依

首先使用在您的应用程序中创建一个模型php artisan make:model Product那么您所要做的就是使用该模型来查询结果://add Product model namespace on the topuse 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);

子衿沉夜

使用数据库查询来更新您的数据。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]);
打开App,查看更多内容
随时随地看视频慕课网APP