CakePHP:是否可以插入具有预定义主键值的记录? [英] CakePHP: Is it possible to insert record with pre-defined primary key value?

查看:56
本文介绍了CakePHP:是否可以插入具有预定义主键值的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CakePHP模型-用户-与外部公司系统有联系。我在这些系统上存储一些数据,在本地存储其他数据。在我的 User :: beforeSave()方法中,我试图设置一个ID,将数据(带有该自定义ID)发送到我的公司系统,然后,如果它在此成功插入,返回true,以便Cake将使用相同的ID插入新的用户记录,以便以后可以链接它们。

I have a CakePHP model - User - that has ties to an external corporate system. I store some data on those systems and other data locally. In my User::beforeSave() method, I'm trying to set an ID, send the data (with that custom ID) to my corporate systems and then, if it inserts successfully there, return true so that Cake will insert the new user record with that same ID so that I can link them later.

我找不到方法做到这一点。有没有一种方法可以插入带有用户指定的主键值的CakePHP记录?我正在使用UUID,因此(实际上)没有重叠的机会。

I can't find a way to make this happen. Is there a way to insert a CakePHP record with a user-specified primary key value? I'm using UUIDs so there's (effectively) no opportunity for overlap.

$this->data['User']['id'] = String::uuid()

try {
   $user_proxy = new CoreServicesUserProxy();

   $corp_user = $user_proxy->CreateUser (

      array (

         'user' => array (

            'UserName'     => 'myusername',

            'EmailAddress' => $this->data['User']['email'],

            'SecurityId'   => $this->data['User']['id']

         )

      )

   );
}
catch ( Exception $e ) {
   // error handling stuff
   return false;
}


推荐答案

我知道您已经得到了一些提示,

I realise you have already been given some hints, but here is some code which might help.

为什么不在 external_user_id 字段呢? >用户表?

Why not add an external_user_id field to your users table?

<?php
class User extends AppModel {

    function beforeSave() {
        $ds = ConnectionManager::getDataSource('core_services');
        $externalUser = $ds->createUser($this->data);
        if (!$externalUser) {
            return false;
        }
        $this->data['User']['external_id'] = $externalUser['id'];
        return true;
    }

    function afterFind($results, $primary) {
        // handle different types of find here ('all' vs 'first' vs through relation)
        foreach ($results as &$result) {
            $result = $this->_mergeExternalUser($result);
        }
    }

    function _mergeExternalUser($user) {
        $ds = ConnectionManager::getDataSource('core_services');
        $externalUser = $ds->retrieveUser($result['external_id']);
        return am($externalUser, $user);
    }

}
?>

这篇关于CakePHP:是否可以插入具有预定义主键值的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆