关联和模型数据保存问题

时间:2010-04-08 17:48:06

标签: cakephp associations tagging

使用cakephp 1.3进行开发(最新来自github)。 有两个模型与hasAndBelongsToMany绑定:文档和标签。换句话说,文档可以有许多标签。我添加了一个新文档提交表单,用户可以在其中输入用逗号分隔的标签列表(如果不存在则添加新标签)。我在github上看了cakephp面包店2.0 source code并找到了解决方案。但似乎有些事情是错的。

class Document extends AppModel {
public $hasAndBelongsToMany = array('Tag');
public function beforeSave($options = array()) {
                if (isset($this->data[$this->alias]['tags']) && !empty($this-
>data[$this->alias]['tags']))

                {
                        $tagIds = $this->Tag->saveDocTags($this->data[$this->alias]
['tags']);
                        unset($this->data[$this->alias]['tags']);
                        $this->data[$this->Tag->alias][$this->Tag->alias] = $tagIds;
                }
                return true;
        }

}

class Tag extends AppModel {
    public $hasAndBelongsToMany = array ('Document');

   public function saveDocTags($commalist = '') {
        if ($commalist == '') return null;
        $tags = explode(',',$commalist);
        if (empty($tags)) return null;
        $existing = $this->find('all', array(
            'conditions' => array('title' => $tags)
        ));
        $return = Set::extract($existing,'/Tag/id');
        if (sizeof($existing) == sizeof($tags)) {
            return $return;
        }
        $existing = Set::extract($existing,'/Tag/title');
        foreach ($tags as $tag) {
            if (!in_array($tag, $existing)) {
                $this->create(array('title' => $tag));
                $this->save();
                $return[] = $this->id;
            }
        }
        return $return;
    }

} 

因此,新标签创建效果很好,但文档模型无法保存关联数据并告知: SQL错误:1054:“字段列表”中的未知列“数组” 查询:INSERT INTO documentstitlecontentshortnfodatestatus)VALUES('带标签的文档','','',数组,1) 任何想法如何解决这个问题?

P.S。从firebug发布此表单的数据: _method POST 数据[文件] [内容]测试文件内容 数据[文件] [日期] [年] 2010年 data [Document] [shortnfo]关于文档的简短信息 数据[文件] [状态] 1 data [Document] [tags]测试,类别,列表 数据[文件] [标题]测试题目 我们看不到任何数组。

1 个答案:

答案 0 :(得分:0)

解决! :)问题出在视图中:

'date'=>array('label'=>'Date', 'type'=>'date', 'dateFormat'=>'Y'),

但数据库中的日期字段。这个字段的类型是年份。