我有phalcon模型魔术吸气剂和二传手的问题。 我想像本教程一样更新: https://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records
但事情是我的proj是多模块和分离模型文件夹。
所以我必须为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();
但是在此代码之上只保存用户数据,根本不保存配置文件数据。 (有个人资料数据 - 已确认)
那你知道错误是什么吗?如果你知道,请帮助我或给我一个提示。
答案 0 :(得分:1)
我现在得到了..当分配像$ 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的提示......:)
答案 1 :(得分:0)
而不是做
$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();
请注意,这将始终创建新 UserProfile
。如果您想使用相同的代码来更新和创建UserProfile
,您可以执行以下操作:
// ...
// instantiate a (new) profile and assign its data
$profile = UserProfile::findFirstByUserId($user->getUserId());
if (!$profile) {
$profile = new UserProfile();
}
$profile->assign($newProfileData);
// ...