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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵