2014-10-17 49 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); 
    } 
}