【发布时间】: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 总是有相同的值。
【问题讨论】:
-
旁注:切勿实例化
new Model()之类的模型,使用ClassRegistry::init()、Controller::loadModel()或定义要加载到Controller::$uses中的模型。 -
创建方法没有帮助:(