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 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。