Cakephp保存数据并读取MAX

时间:2015-03-17 12:03:00

标签: cakephp save max

我正试图以这种方式在CakePHP中保存数据:

  1. 从表格翻译中获取max entry_id

    (SELECT MAX(entry_id) as res FROM translations) + 1
    
  2. 将数据保存到翻译表

    $translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
    $translation = new Translation();
    $translation->set($translationData);
    $translation->save();
    
  3. 再次获得最高entry_id

  4. 保存下一组数据
  5. 再次获得最多entry_id
  6. 保存下一组数据
  7. 请查看我的代码:

        $this->request->data['Product']['name_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['name']);
        $this->request->data['Product']['description_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['description']);
        $this->request->data['Product']['seo_title_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_title']);
        $this->request->data['Product']['seo_keywords_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_keywords']);
        $this->request->data['Product']['seo_desc_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_desc']);
    

    saveTranslations方法:

    public function saveTranslations($data) {
        $entry_id = $this->getNextFreeId();
    
        foreach($data as $key => $item) {
            if($item != "") {
                $this->create();
                $temp['Translation']['entry_id'] = $entry_id;
                $temp['Translation']['language_id'] = $key;
                $temp['Translation']['text'] = $item;
                $this->save($temp);
            }
        }
        return $entry_id;
    }
    

    getNextFreeId方法:

    public function getNextFreeId() {
        $result = $this->query("SELECT MAX(entry_id) as res FROM translations");
        return $result[0][0]['res'] + 1;
    }
    

    我不知道为什么entry_id始终具有相同的值。

1 个答案:

答案 0 :(得分:1)

经过几个小时的搜索解决方案后,我终于设法以非常简单的方式解决了问题 - 只需在查询方法中添加 false 参数:

$this->query("INSERT INTO translations(entry_id, language_id, text) VALUES($entry_id, $key, '$item')", false);

$result = $this->query("SELECT SQL_CACHE MAX(entry_id) as res FROM translations", false);