phalcon 2.0.13 将魔法 setter 的数据设置为相关模型

phalcon 2.0.13 set data with magic setter to related model

我对 phalcon 模型魔术 getter 和 setter 有疑问。 我想像本教程一样更新: https://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records

但问题是我的项目是多模块和独立的模型文件夹。

所以我必须为 hasOne 和 belongsTo 使用别名

$this->hasOne('user_id', '\Models\UserProfile', 'user_id', array('alias' => 'UserProfile'));

 $this->belongsTo('user_id', '\Models\CoreUser', 'user_id', array('alias' => 'CoreUser'));

我想做的是这样的

$CoreUser = new CoreUser();
$user = $CoreUser->findFirst(array(
        //...condition here to find the row i want to update
     ));

$user->assign($newUserData);

$user->setUserProfile($newProfileData); 

$user->update();

但上面这段代码只保存用户数据,根本不保存个人资料数据。 (有个人资料数据 -- 已确认)

所以你知道错误是什么吗?如果你知道,请帮助我或给我提示。

我现在知道了.. 像 $user->UserProfile = $newUserProfile; 这样分配时 $newUserProfile 应该是一个模型对象。

所以我的新密码是

$CoreUser = new CoreUser();

$user = $CoreUser->findFirst(array(
    //...condition here to find the row i want to update
 ));
$profile = $user->UserProfile; //$profile is now model object which related to $user

//assign new array data 
$profile->assign($newProfileData);
$user->assign($newUserData);
/*
* can also assign one by one like
* $user->first_name = $newProfileData['first_name'];
* but cannot be like $profile = $newProfileData or $user->UserProfile = $newProfile
* since it's gonna override it the model with array
*/
$user->UserProfile = $profile;   

$user->update(); // it's working now

也感谢@Timothy 的提示..:)

而不是

$profile = $user->UserProfile;

您应该实例化一个新的 UserProfile 对象

// find your existing user and assign updated data
$user = CoreUser::findFirst(array('your-conditions'));
$user->assign($newUserData);

// instantiate a new profile and assign its data
$profile = new UserProfile();
$profile->assign($newProfileData);

// assign profile object to your user
$user->UserProfile = $profile;

// update and create your two objects
$user->save();

请注意,这将始终创建一个 new UserProfile。如果您想使用相同的代码来更新和创建 UserProfile,您可以这样做:

// ...

// instantiate a (new) profile and assign its data
$profile = UserProfile::findFirstByUserId($user->getUserId());

if (!$profile) {
    $profile = new UserProfile();
}

$profile->assign($newProfileData);

// ...