我有一个有两种关系的用户模型:
//User model
function profile() {
return $this->hasOne(Profile::class);
}
public function photos() {
return $this->hasMany(Photo::class);
}
我想在创建用户时保存关系数据。
想法是在保存用户之前发送一个事件,并更改一些关系数据
类似的东西:
$profile = new Profile;
$profile->fill($profileData); // I don't want to persist it right now
$photos = [];
foreach ($photosData as $photoData) {
$photo = new Photo;
$photo->fill($photoData);
$photos[] = $photo;
}
$user = new User;
$user->data = "data";
$user->profile() // Do something
$user->photos() // Do something
event(new UserWillBeCreated($user));
$user->save(); // this will create in database Profile, Photos and user
在我的活动的监听者中,我可以在保存之前更新个人资料数据
$user->profile->name = "another name";