2014-10-17 61 views
6

Yii2(稳定)有问题。我有一个标记(PK:id)表,我有一个名为Content_Tag(PK:content_id,tag_id)的联结表。我有一个标记(PK:id)表。我想用它来标记,比如WP标签。Yii2 - 插入关系数据与连接表,多连接

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

我有两个问题:

如果我创建一个新的内容,我想通过Content_Tag表保存了一些新的标签来标记表。我怎样才能做到这一点?用链接()?

如果标签表中有标签(我知道标识符),那么我想通过联结表仅连接到内容表,而不插入到标签表中。我怎样才能做到这一点?

我不想编写原生SQL命令,我想使用内置在链接()或via()或viaTable()函数中的Yii2。

感谢您的帮助!

+0

你可以看看这里:http://www.yiiframework.com/forum/index.php/topic/52592-handling-many-to-many-relation/ – robsch 2014-10-17 09:28:32

回答

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()来保存。我也在寻找那个,因为我没有使用它。

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