【问题标题】:Inserting new row instead of Updating插入新行而不是更新
【发布时间】:2015-02-05 12:19:11
【问题描述】:

我正在尝试更新数据库中的配置文件而不将配置文件 ID 作为参数传递,而不是更新我正在添加新行。我尝试使用 getLastInsertId() 但它不起作用。

public function editProfile(){

    if (isset($this->data)){

        $Client = $this->Client->find('first', array(
        'fields' => array('email','username','first_name','surname','country','phone_prefix','phone'),
        'conditions' => array(
            'Client.email' => $this->request->query['email'],
            'Client.client_type' => $this->request->query['client_type']
             ),
        )
    );


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

        if($data = $this->Client->save($this->request->query,array('first_name','surname','country','phone_prefix','phone')))
        {
            $this->Client->id = $this->Client->getLastInsertId();

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-1.3 cakephp-2.3


    【解决方案1】:

    您似乎正在尝试根据电子邮件和客户端类型更新客户端模型中的记录,因为(我假设)您不知道 id。

    尝试更改您的代码以根据您拥有的信息获取 id -

    public function editProfile(){
    
    if($this->request->is('get')) {
      if (isset($this->data)){
    
        $conditions = array('conditions' => array(
                'email' => $this->request->query['email'],
                'client_type' => $this->request->query['client_type']
             ));
        $this->Client->id = $this->Client->field('id', $conditions);
    
        if($this->Client->save($this->request->query,array('id', 'first_name','surname','country','phone_prefix','phone')))
        {
          $this->setFlash('success');
        }else{
          $this->setFlash('fail');
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      查看代码,您似乎有两个可能的键:

      1. 客户电子邮件
      2. 最后保存的id

      首先,使用最后保存的 id 似乎很脆弱 - 您如何确定这将始终是您要更新的记录?最好避免这种方法。

      但是,如果您有用户的电子邮件,您可以使用以下方法:

      $client = $this->Client->findByEmail($this->request->data['Client']['email']);
      $id = $client['Client']['id'];
      

      您现在可以在保存中使用客户端记录 ID。比如:

      $data = array();
      $data['Client']['id'] = $id;
      $data['Client']['fieldFromForm'] = $this->data['Client']['fieldFromForm'];
      
      $this->Client->save($data);
      

      ...

      【讨论】:

        【解决方案3】:

        如果没有 id,cake 将假定您正在添加一个新客户端。要通过保存进行更新,您需要以某种方式告诉它要更新哪个 Client.id。是否有某些原因您不能提供 Client.id?通常的方法是让 Client.id 出现在编辑视图的隐藏输入中,然后您可以将其传递给编辑操作...

        【讨论】:

        • 我添加了这一行并且它有效。 $this->request->query['id'] = $Client['Client']['id.'] 谢谢回复
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多