I have a model contents
that has a many to many relationship with tags
through the intermediary table contents_tags
. When I insert a new row in contents
I want to also add multiple tags. While this works fine, I want the tags
entries to be unique, so they will be inserted if they are new, or updated (although nothing changes) if they already exist.
This unit test seems to imply that this can be done automatically, but I can't manage to replicate the same behaviour. If I don't have a unique index on my tag table, then I get multiple of the same entries. If I do then the tag model throws an error.
This is my test code:
$content = new Content();
$content->title = 'xkcd';
$content->description = 'description goes here';
$content->url = 'https://xkcd.com/';
$content->created_on = new Phalcon\Db\RawValue('NOW()');
$content->tags = array();
$tagsText = 'xkcd,comics,testing';
$tags = array();
foreach(explode(',', $tagsText) as $tagText) {
$tag = new Tag();
$tag->tag = trim($tagText);
$tags[] = $tag;
}
$content->tags = $tags;
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()));
}
Contents model:
class Content {
public function initialize() {
$this->hasManyToMany(
'id',
'ContentsTags',
'content_id',
'tag_id',
'Tag',
'id',
array('alias' => 'tags')
);
}
public function getSource() {
return 'contents';
}
}
ContentsTag model:
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';
}
}
Tag model:
class Tag {
public function getSource() {
return 'tags';
}
public function initialize() {
$this->hasManyToMany(
'id',
'ContentsTags',
'tag_id',
'content_id',
'Content',
'id',
array('alias' => 'contents')
);
}
}
Example data from the tables:
contents:
+----+-------+-----------------------+------------------+
| id | title | description | url |
+----+-------+-----------------------+------------------+
| 11 | xkcd | description goes here | https://xkcd.com/ |
+----+-------+-----------------------+------------------+
contents_tags:
+----+------------+--------+
| id | content_id | tag_id |
+----+------------+--------+
| 1 | 11 | 1 |
| 2 | 11 | 2 |
+----+------------+--------+
tags:
+----+--------+
| id | tag |
+----+--------+
| 1 | comics |
| 2 | maths |
+----+--------+
The models for the unit test mentioned above seem to have no special parameters set, and I can't find the actual table declarations for them so I am at a bit of a loss. The models for the unit test can be seen here: