I know that I can insert multiple records in laravel with:
$data = [
['name' => '...', 'age' => ...],
['name' => '...', 'age' => ...],
['name' => '...', 'age' => ...],
];
Model::insert($data);
But is is possible to do a bulk insert that also has a one-to-one relation? So that I insert data into two databases at the same time?
Something like:
$data = [ ['name' => '...', 'age' => ...], ['name' => '...', 'age' => ...], ['name' => '...', 'age' => ...], ];
Model::withSecondTable()->insert($data);
Yes it is possible. For example:
###User Model:
public function item()
{
return $this->belongsTo('Item');
}
###Item Model:
public function users()
{
return $this->hasMany('User');
}
To save a User from the Item perspective, you do this:
$item->users()->save($user);
To associate an item with a user, you do this:
$user->item()->associate($item);
$user->save();
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.