【问题标题】:Saving related models in Phalcon on a manyToMany (N-N) relationship在多对多 (N-N) 关系上保存 Phalcon 中的相关模型
【发布时间】:2014-09-18 11:40:47
【问题描述】:

我有三个数据库表; contentscontents_tagstags。我想向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"}

谁能看出我在哪里搞砸了?

【问题讨论】:

    标签: model phalcon


    【解决方案1】:

    原来我找错地方了。您不能以这种方式将相关项目作为数组处理,您必须这样做:

    $tags = array();
    foreach(explode(',', $tagsText) as $tagText) {
        $tag = new Tag();
        $tag->tag = trim($tagText);
        $tags[] = $tag;
    }
    $content->tags = $tags;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      相关资源
      最近更新 更多