I'm trying to update multiple models at once, I didn't tried any function so far, but I would not if there is no way of doing it. For example, I have model Products and there is few relations, with another relations inside. And I'm getting it like this:
Products::where('id', $id)->with('category', 'info.country', 'images', 'packages.package.info.country')->firstOrFail()
So is there any way to make update function at once? For example
Products::where('id', $id)->with('category', 'info.country', 'images', 'packages.package.info.country')->firstOrCreate($request);
Is that possible?
You can't update multiple models with a single statement as you can't update multiple tables in one SQL statement. However, you can use a transaction to make sure that all statements are treated atomically.
DB::beginTransaction();
try {
$product = Product::find($id);
$product->category()->update([
'name' => 'Category 1',
]);
// rest of the statements
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.