Cakephp 保存数据并读取 MAX
Posted
技术标签:
【中文标题】Cakephp 保存数据并读取 MAX【英文标题】:Cakephp save data and read MAX 【发布时间】:2015-03-17 12:02:59 【问题描述】:我正在尝试以这种方式在 Cakephp 中保存数据:
从表翻译中获取最大 entry_id
(SELECT MAX(entry_id) as res FROM translations) + 1
将数据保存到翻译表中
$translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
$translation = new Translation();
$translation->set($translationData);
$translation->save();
再次获得最大值entry_id
entry_id
保存下一组数据
请看我的代码:
$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
总是有相同的值。
【问题讨论】:
看看book.cakephp.org/2.0/en/models/… 旁注:切勿实例化new Model()
之类的模型,使用 ClassRegistry::init()
、Controller::loadModel()
或定义要加载到 Controller::$uses
中的模型。
创建方法没有帮助:(
【参考方案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);
【讨论】:
以上是关于Cakephp 保存数据并读取 MAX的主要内容,如果未能解决你的问题,请参考以下文章