📅  最后修改于: 2023-12-03 15:02:35.366000             🧑  作者: Mango
Laravel is a popular PHP framework that provides convenient and easy to use functions to work with databases. One of the main features of Laravel is its built-in ORM (Object Relational Mapping) called Eloquent. In this tutorial, we will learn how to use Eloquent to update records in a database table based on a condition using Laravel's where()
method.
Before proceeding with this tutorial, you should have:
To update records in a database table based on a condition using Eloquent, we can use the where()
method followed by the update()
method. Here is an example:
$affectedRows = User::where('status', 1)
->update(['points' => 100]);
In this example, we are updating the points
field of all users whose status
field is 1. The update()
method returns the number of affected rows, which we store in the $affectedRows
variable.
We can also update multiple fields at once using the update()
method. Here is an example:
$affectedRows = User::where('status', 1)
->update([
'points' => 100,
'level' => 2,
]);
In this example, we are updating the points
and level
fields of all users whose status
field is 1.
In this tutorial, we have learned how to use Laravel's Eloquent to update records in a database table based on a condition using the where()
method. This is a powerful feature of Laravel that makes it easy to work with databases in an object-oriented way.