【问题标题】:Cakephp save data and read MAXCakephp 保存数据并读取 MAX
【发布时间】:2015-03-17 12:02:59
【问题描述】:

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

  1. 从表翻译中获取最大 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. 保存下一组数据

请看我的代码:

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

【问题讨论】:

  • 旁注:切勿实例化 new Model() 之类的模型,使用 ClassRegistry::init()Controller::loadModel() 或定义要加载到 Controller::$uses 中的模型。
  • 创建方法没有帮助:(

标签: cakephp save max


【解决方案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);

【讨论】:

    猜你喜欢
    • 2019-06-23
    • 2011-09-14
    • 2013-09-24
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2021-10-29
    • 2018-02-24
    • 1970-01-01
    相关资源
    最近更新 更多