Yii2 - 使用连接表插入关系数据,许多连接

时间:2014-10-17 04:52:35

标签: yii2

我遇到Yii2(稳定版)的问题。

我有一个Content(PK:id)表,我有一个Tag(PK:id)表,我有一个名为Content_Tag的联结表(PK:content_id,tag_id)。我想用它来标记,就像WP标签一样。

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

我有两个问题:

如果我创建新内容,我想通过Content_Tag表将一些新标签保存到Tag表中。我怎样才能做到这一点?使用link()?

如果标签表中有标签(我知道ID),我想通过联结表只与Content表连接,而不插入Tag表。我怎么能这样做?

我不想编写本机SQL命令,我想使用Yii2内置函数,如link()或via()或viaTable()。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

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

$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);
    }
}

答案 1 :(得分:0)

如果您使用gii创建模型,那么您可能会在模型中看到关系完成如下:

 /**
 * @return \yii\db\ActiveQuery
 */
public function getContent()
{
    return $this->hasMany(Content_Tag::className(), ['content_id' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getContent()
{
    return $this->hasMany(Tag::className(), ['tag_id' => 'tag_id'])->viaTable('content_tag', ['content_id' => 'id']);
}

如果你想根据内容和标签表保存在Content_Tag表中,那么在控制器中你可以使用:

public function actionCreate()
  {
    $model          = new Tag();
    $content          = new Content();
    $content_tag = new Content_tag();

    if($model->load(Yii::$app->request->post()) && $model->save()){
      $model->save(false);
      $content_tag->tag_id = $model->id;
      $content_tag->content_id = $model->content_id;
      $content_tag->save(false);
      if($model->save(false))
      {
        Yii::$app->getSession()->setFlash('success', 'Created successfully');
        return $this->render('create',[
            'model' => $model,
            'content' => $content,
            'content_tag' => $content_tag
          ]);
      }
    }
    else
    {
      return $this->render('create', [
          'model' => $model,
        ]);
    }
  }

您可以使用link()进行保存。我也在搜索,因为我没有使用它。