PHP code example of rkit / tags-behavior-yii2
1. Go to this page and download the library: Download rkit/tags-behavior-yii2 library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rkit / tags-behavior-yii2 example snippets
$this->createTable('{{%tag}}', [
'id' => $this->primaryKey(),
'name' => $this->string()->notNull()->unique(),
'frequency' => $this->integer()->notNull()->defaultValue(0),
]);
$this->createTable('{{%post_to_tag}}', [
'post_id' => $this->integer()->notNull()->defaultValue(0),
'tag_id' => $this->integer()->notNull()->defaultValue(0),
]);
$this->addPrimaryKey('', '{{%post_to_tag}}', ['post_id', 'tag_id']);
public function behaviors()
{
return [
'tagsBehavior' => [
'class' => 'rkit\tags\behavior\TagsBehavior',
'relation' => 'tags',
'tagAttribute' => 'name',
'tagFrequencyAttribute' => 'frequency', // or false
'findTag' => function ($value) {
return Tag::find()->where([$this->tagAttribute => $value])->one();
},
'createTag' => function ($value) {
$tag = new Tag();
$tag->{$this->tagAttribute} = $value;
return $tag;
},
],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTags()
{
return $this
->hasMany(Tag::class, ['id' => 'tag_id'])
->viaTable('{{%post_to_tag}}', ['post_id' => 'id']);
}
$model = new Post();
$model->setTagValues(['example1', 'example2']);
$model->save();
$post = Post::find()->with('tags')->where(['id' => $id])->one();
$post->getTagValues();
$model = new Post();
$model->setTagValues([]);
$model->save();