Yii2 - 使用连接表插入关系数据,多对多连接 [英] Yii2 - insert relational data with junction table, many-many connection

查看:35
本文介绍了Yii2 - 使用连接表插入关系数据,多对多连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Yii2(稳定版)时遇到问题.

I have a problem with Yii2 (Stable).

我有一个 Content(PK:id) 表,我有一个 Tag(PK:id) 表,还有一个名为 Content_Tag (PK:content_id, tag_id) 的连接表.我想用它来做标签,比如 WP 标签.

I have a Content(PK:id) table, I have a Tag(PK:id) table, and I have a junction table called Content_Tag (PK:content_id, tag_id). I'd like to use it for tagging, like WP tags.

所有控制器和模型都是用 gii 创建的.

All controllers and models are created with gii.

我有两个问题:

如果我创建了一个新内容,我想通过 Content_Tag 表将一些新标签保存到 Tag 表中.我怎样才能做到这一点?带链接()?

If I create a new content, I'd like to save some new tags to the Tag table via the Content_Tag table. How can I do that? With link()?

如果标签表中有标签(我知道id)怎么办,我只想通过连接表连接内容表,而不插入标签表.我该怎么做?

What if there are tags (I know the ids) in the tag table, I'd like to connect only with the Content table via the junction table, without inserting into the Tag table. How can I do this?

我不想编写原生 SQL 命令,我想使用 Yii2 内置函数,如 link() 或 via() 或 viaTable().

I don't want to write native SQL command, I'd like to use the Yii2 built in functions like link() or via() or viaTable().

感谢您的帮助!

推荐答案

我创建了一个行为来帮助处理这样做,基本上你这样做:

I created a behavior to help handle do this, basically you do:

$content = Content::findOne(1);
$tags = [Tag::findOne(2), Tag::findOne(3)];
$content->linkAll('tags', $tags, [], true, true);

您可以在此处获取行为:https://github.com/cornernote/yii2-linkall

You can get the behavior here: https://github.com/cornernote/yii2-linkall

如果您更愿意在没有行为的情况下执行此操作,请执行以下操作:

If you'd prefer to do it without the behavior, something like this:

// 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 - 使用连接表插入关系数据,多对多连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆