【问题标题】:Manually setting ID when using saveAssociated in CakePHP 2在 CakePHP 2 中使用 saveAssociated 时手动设置 ID
【发布时间】:2012-06-25 19:43:59
【问题描述】:

我有以下表格:

        echo $this->Form->input('Person.name');
        echo $this->Form->input('Person.phone');
        echo $this->Form->input('Person.email');
        echo $this->Form->input('Message.0.plainmsg');
        echo $this->Form->submit('Send Message');
        echo $this->Form->end();

Person 有很多Message

我想设置控制器,以便第一次填写表格时 PersonMessage 被插入,但第二次有人使用相同的电子邮件地址填写表格时,Person 只是已更新,但像以前一样插入了新的 Message

这是我的控制器到目前为止的样子:

    if ($this->request->is('post')) {

        // Check to see if submitted email address is already
        // a record in Person model
        $person = $this->Person->findByEmail($this->request->data['Person']['email']);

        if ($person) {
            // Set the ID (save query will be UPDATE)
            $this->Person->id = $person['Person']['id'];
        } else {
            // Create a new record (save query will be INSERT)
            $this->Person->create();
        }

        // Save the data (will run as UPDATE or INSERT
        // depending on above
        $this->Person->save($this->request->data);
    }

这一切都按预期工作:如果Person.email 已经存在,那么Person 将被更新而不是被插入。这正是我想要的。

问题是我无法弄清楚如何将Message 用于所有这些。

我尝试将保存更改为$this->Person->saveAssociated($this->request->data),如this section of the cake manual 中的最后一个示例所示,但结果是蛋糕尝试插入Person 而不是更新它。

我在这里尝试做的重点和目的是允许用户发布无限数量的新Message 并始终使用他们当前的联系号码更新他们的Person 记录(这将定期更改基础)。

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    您应该使用参数$personId$messageText 在消息模型中创建一个方法saveMessage。 此方法的逻辑是将您的新消息与所属用户一起保存。

    在您调用Person::save() 之后,无论您创建还是更新了Person,Person ID 都将保存在$this->Person->id

    在这种情况下,我不会使用任何蛋糕魔法。

    【讨论】:

    • 是的,你是对的,这是处理这个问题的最好方法。我刚刚这样实现了它,它很有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多