doukanwen4114 2016-08-09 10:31 采纳率: 100%
浏览 54
已采纳

phalcon 2.0.13使用魔术设定器将数据设置为相关模型

I have a problem with phalcon model magic getter and setter. I want to update like this tutorial : https://docs.phalconphp.com/en/latest/reference/models.html#storing-related-records

But the thing is my proj is multi module and separated models folder.

So I have to use alias for hasOne and belongsTo

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

and

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

What i want to do is like this.

$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();

But above this code only save user data and don't save Profile data at all. (have profile data -- confirmed)

So do you have any idea what the error is? if u know, Please help me or give me a tip.

  • 写回答

2条回答 默认 最新

  • duanbo7517 2016-08-10 10:44
    关注

    Instead of doing

    $profile = $user->UserProfile;
    

    You should instantiate a new UserProfile object

    // 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();
    

    Note that this will always create a new UserProfile. If you want to use the same code to update and create a UserProfile, you can maybe do something like:

    // ...
    
    // instantiate a (new) profile and assign its data
    $profile = UserProfile::findFirstByUserId($user->getUserId());
    
    if (!$profile) {
        $profile = new UserProfile();
    }
    
    $profile->assign($newProfileData);
    
    // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?