我在使用 Yii2(稳定版)时遇到问题。
我有一个 Content(PK:id) 表、一个 Tag(PK:id) 表和一个名为 Content_Tag (PK:content_id, tag_id) 的联结表。我想用它来标记,例如 WP 标记。
所有 Controller 和模型都是用gii创建的。
我有两个问题:
如果我创建新内容,我想通过 Content_Tag 表将一些新标签保存到 Tag 表中。我怎样才能做到这一点?使用链接()?
如果标签表中有标签(我知道 id)怎么办,我想通过联结表仅与内容表连接,而不插入标签表。我怎样才能做到这一点?
我不想编写原生 SQL 命令,我想使用 Yii2 内置函数,如 link() 或 via() 或 viaTable()。
感谢您的帮助!
最佳答案
我创建了一个行为来帮助处理这个问题,基本上你会这样做:
$content = Content::findOne(1);
$tags = [Tag::findOne(2), Tag::findOne(3)];
$content->linkAll('tags', $tags, [], true, true);
您可以在此处获取行为: https://github.com/cornernote/yii2-linkall
如果您不想这样做,请像这样:
// get the content model
$content = Content::findOne(1);
// get the new tags
$newTags = [Tag::findOne(2), Tag::findOne(3)];
// get the IDs of the new tags
$newTagIds = ArrayHelper::map($newTags, 'id', 'id');
// get the old tags
$oldTags = $post->tags;
// get the IDs of the old tags
$oldTagIds = ArrayHelper::map($oldTags, 'id', 'id');
// remove old tags
foreach ($oldTags as $oldTag) {
if (!in_array($oldTag->id, $newTagIds)) {
$content->unlink('tags', $oldTag, true);
}
}
// add new tags
foreach ($newTags as $newTag) {
if (!in_array($newTag->id, $oldTagIds)) {
$content->link('tags', $newTag);
}
}
关于Yii2 - 使用联结表插入关系数据,多对多连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26418101/