Cakephp保存数据和读取MAX

Cakephp save data and read MAX

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

  1. 从 table 翻译中获取最大值 entry_id

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

    $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. 保存下一组数据

请看我的代码:

    $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 总是有相同的值。

经过数小时的寻找解决方案,我终于设法以非常简单的方式解决了问题 - 只需在查询方法中添加 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);