douna1892 2015-10-03 11:08
浏览 18

cakephp 1.3中的查询和更新

would like to update attached_blog_id field to set NULL. Thank you in advance.

 foreach($this->Event->find('all', array('conditions' => array('Event.attached_blog_id' => $this->id()))) as $attached_blog)
   $this->Event->query('UPDATE armo8427_events' . ' SET attached_blog_id = NULL' . ' WHERE id = ' . $attached_blog['Event']['id']);
  • 写回答

1条回答 默认 最新

  • douluanzhao6689 2015-10-03 14:01
    关注

    Don't use query unnecessarily

    The code in the question would be better written as:

    $events = $this->Event->find(
        'all', 
        array(
            'conditions' => array(
                'Event.attached_blog_id' => $this->id()
            )
        )
    );
    
    foreach($events as $event) {
        $this->Event->id = $event['Event']['id'];
        $this->Event->saveField('attached_blog_id', null);
    }
    

    With the code-logic in the question there is no need to use query at all

    But be efficient

    The logic in the question can be expressed as a single sql query, instead of 1+n:

    UPDATE
        events
    SET
        attached_blog_id = NULL
    WHERE
        attached_blog_id = $id;
    

    I.e. if there were 100 linked blogs, using the foreach loop will issue 101 queries, wheras this is the same in one query irrespective of the number rof affected rows.

    The most appropriate way to do that in CakePHP is to use updateAll:

    $id = $this->id(); // From the question
    $this->Event->updateAll(
        array('Baker.attached_blog_id' => null), // the update
        array('Baker.attached_blog_id' => $id) // conditions to match
    );
    

    the method query should be reserved for sql calls which are not possible to achieve using the provided model methods.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起