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 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00