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

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]);
- 2 回答
- 0 關注
- 116 瀏覽
添加回答
舉報