我有三个数据库表; contents
,contents_tags
和tags
。我想向contents
添加一个新条目,但我一直收到错误Cursor is an immutable ArrayAccess object
。
我一直关注this section of the manual regarding saving related records。这forum post concerning setting up the relationships。一切都无济于事。我认为它类似于课堂名称上的复数形式,但我无法看到它。
这是我的测试代码:
$content = new Content();
$content->title = 'xkcd';
$content->description = 'description goes here';
$content->url = 'http://xkcd.com/';
$content->created_on = new Phalcon\Db\RawValue('NOW()');
$content->tags = array();
$tagsText = 'xkcd,comics,testing';
foreach(explode(',', $tagsText) as $tagText) {
$tag = new Tag();
$tag->tag = trim($tagText);
$content->tags[] = $tag;
}
if($content->save()) {
$app->response->setStatusCode(201, "Created");
$app->response->setJsonContent($content->overview());
} else {
$app->response->setStatusCode(400, "Bad Request");
$app->response->setJsonContent(array('errors'=>$content->getMessagesAsArray()));
}
内容模型:
class Content {
public function initialize() {
$this->hasManyToMany(
'id',
'ContentsTags',
'content_id',
'tag_id',
'Tag',
'id',
array('alias' => 'tags')
);
}
public function getSource() {
return 'contents';
}
}
ContentsTag模型:
class ContentsTags {
public function initialize() {
$this->belongsTo('content_id', 'Content', 'id', array('alias' => 'content'));
$this->belongsTo('tag_id', 'Tag', 'id', array('alias' => 'tag'));
}
public function getSource() {
return 'contents_tags';
}
}
标记模型:
class Tag {
public function getSource() {
return 'tags';
}
public function initialize() {
$this->hasManyToMany(
'id',
'ContentsTags',
'tag_id',
'content_id',
'Content',
'id',
array('alias' => 'contents')
);
}
}
最终输出:
{"error":"Cursor is an immutable ArrayAccess object"}
谁能看到我弄乱的地方?
答案 0 :(得分:0)
事实证明我在找错了地方。您不能以这种方式将相关项目作为数组进行处理,您必须这样做:
$tags = array();
foreach(explode(',', $tagsText) as $tagText) {
$tag = new Tag();
$tag->tag = trim($tagText);
$tags[] = $tag;
}
$content->tags = $tags;