亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 116 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號