Association and model data saving problem
Posted
by Zhlobopotam
on Stack Overflow
See other posts from Stack Overflow
or by Zhlobopotam
Published on 2010-04-08T17:48:05Z
Indexed on
2010/04/08
17:53 UTC
Read the original article
Hit count: 319
Developing with cakephp 1.3 (latest from github). There are 2 models bind with hasAndBelongsToMany: documents and tags. Document can have many tags in other words. I've add a new document submitting form there user can enter a list of tags separated with commas (new tag will be added, if not exist already). I looked at cakephp bakery 2.0 source code on github and found the solution. But it seems that something is wrong.
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;
}
}
So, new tags creation works well but document model can't save association data and tells:
SQL Error: 1054: Unknown column 'Array' in 'field list'
Query: INSERT INTO documents
(title
, content
, shortnfo
,
date
, status
) VALUES ('Document with tags', '', '', Array, 1)
Any ideas how to solve this problem?
© Stack Overflow or respective owner