-
Notifications
You must be signed in to change notification settings - Fork 0
Upserting Data
DatabaseFactory gives developers the ability to
upsertdata. This means that we can pass an array of data into a method and either have that data create a new record (insert) or update an existing record (update). In order to create or update data using the ORM system, you need to add theHasUpserttrait to your Entity
class User extends DatabaseFactory\Entity
{
use DatabaseFactory\ORM\HasUpsert;
}From here, you can very easily call the
uspert()method from the entity you're working with to either add a new record, or modify an existing one.
$data = [
'name' => 'John Smith',
'email' => '[email protected]',
'password' => Str::bcrypt('password'),
];
# add a new record
User::upsert(data: $data);
# OR
# modify an existing record by passing
# through its ID
User::upsert(data: $data, id: 10);The
upsert()method also accepts a callback function as thecallbackparameter. This will return an entity object of the record you are working with.
$data = [
'name' => 'John Smith',
'email' => '[email protected]',
'password' => Str::bcrypt('password'),
];
User::upsert(data: $data, callback: function($user) {
echo $user->name; // 'John Smith'
});Creating new data and adding it to your database is extremely simple. All we need to do is create a new entity object, and assign values to its fields. From there, we call the
save()method to save the record.
# create a new entity object
$user = new User();
# assign values to the entities properties
$user->name = 'Georges St. Pierre';
$user->email = '[email protected]';
$user->password = Str::bcrypt('password');
# save the record
$user->save();Updating a record is virtually identical to creating a new one. The main difference here is that we will be passing an ID into the constructor of the entity object which represents the record we are working with
# create a new entity object and pass the ID
# into the constructor
$user = new User(15);
# assign values to the entities properties
$user->name = 'Anderson Silva';
$user->email = '[email protected]';
$user->password = Str::bcrypt('password');
# save the record
$user->save();