doukanwen4114 2016-08-09 10:31
浏览 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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮