【问题标题】:CakePHP hasOne belongsTo relationship, edit/add same actionCakePHP hasOne belongsTo 关系,编辑/添加相同动作
【发布时间】:2013-06-04 16:40:52
【问题描述】:

使用 CakePHP 2.3。我正在创建一个应用程序,其中有一个用户表和一个配置文件表。关联是这样的:User hasOne Profile / Profile belongsTo User.

但是,我不希望用户有权添加他们的个人资料,因为这可能会产生他们个人资料的副本。我想要一个操作来编辑允许用户的 ONE 配置文件。

有没有办法在添加用户时使用 user_id 和 id 启动配置文件,但所有其他字段为空?这样,用户将在注册时自动拥有关联的个人资料,并且只需要编辑操作来填写空白字段。

如果我能以某种方式使配置文件表中的 id 和 user_id 具有相同的数字,那么在 CakePHP 中会更简洁。请记住,我还需要限制用户只能编辑他们的个人资料。

暂时没有代码,只是希望您对执行此操作的策略提出意见,谢谢!

【问题讨论】:

    标签: php mysql cakephp cakephp-2.3


    【解决方案1】:

    您可以在创建用户时创建配置文件,只需这样做

    //your code for user saving
    if($this->User->save())
       $this->User->Profile->save(array('user_id'=>$this->User->id))
    

    或者那个和tada的变体,空白配置文件被保存。

    事实上,如果您确定总是想为最近创建的用户添加个人资料,您可以在 User 模型的 afterSave 中进行。

    class User extends AppModel {
        public function afterSave($created) {
            //make sure to do it on creation and not on update
            if ($created) {
                $this->Profile->save(array('user_id'=>$this->getLastInsertID());
            }
        }
    }
    

    但请记住,如果您在配置文件模型中设置了验证,这将触发它们。假设您在个人资料中有一个“工作”列,要求不能为空,那么就会出现一些错误。您可以通过在验证过程中添加on 选项来绕过它

    class Profile extends AppModel {
    public $validate = array(
        'job' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'You have to have a job',
                'allowEmpty' => false,
                'required' => true,
                                'on' => 'update'
            )
        ),
                /* etc */
    }
    

    其他选择是简单地......不要那样做:) 如果您不希望用户疯狂地添加配置文件,您可以将其用户 ID“硬编码”到配置文件中。例如,假设您在配置文件控制器中有一个添加操作

    class ProfilesController extends AppController {
    
         public function add($user_id) {
             //lets assume you have the user id somewhere, maybe even get the logged session one
    
             if($this->request->is('post')) {
                 //when you are saving, force the add (or edit) to be for the user_id, not anyone
                 $this->request->data['Profile']['user_id'] = $user_id;
                 $this->Profile->save();
             }
         }
    

    这里和那里有几个 if,没有必要在创建用户后立即创建空白配置文件。不过也不疼……

    如果您确定要在所有用户创建案例中添加空白配置文件,我个人喜欢 afterSave 选项。控制器中的代码更少,但您必须更加小心您的配置文件验证。

    哦,关于配置文件中的“相同 id 和 user_id”……不要那样做。没必要,真的。通过简单的查找,您可以毫无问题地获得用户及其个人资料,让 cake 处理外键。

    【讨论】:

    • 非常感谢,这是一个很好的答案,正是我想要的
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多