rkit / tags-behavior-yii2
Tags Behavior for Yii2
Installs: 6
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- yiisoft/yii2: ^2.0.0
Requires (Dev)
- phpunit/dbunit: ^4.0
- phpunit/phpunit: ^7.2
- squizlabs/php_codesniffer: ^3.3
This package is not auto-updated.
Last update: 2024-11-04 08:34:44 UTC
README
Flexible yii2 behavior for tags.
Requirements
PHP 7
Installation
composer require rkit/tags-behavior-yii2
Configuration
For example, we have a Post
model and we want to add tags.
Let's do it.
- Add
tag
andpost_to_tag
tables and aTag
model for the tags
$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']);
- Add a
TagsBehavior
behavior to thePost
model
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; }, ], ]; }
- Add a
tags
relation (seerelation
option in the behavior)
/** * @return \yii\db\ActiveQuery */ public function getTags() { return $this ->hasMany(Tag::class, ['id' => 'tag_id']) ->viaTable('{{%post_to_tag}}', ['post_id' => 'id']); }
Usage
Add tags
$model = new Post(); $model->setTagValues(['example1', 'example2']); $model->save();
Get tags
$post = Post::find()->with('tags')->where(['id' => $id])->one(); $post->getTagValues();
Remove tags
$model = new Post(); $model->setTagValues([]); $model->save();
Tests
Coding Standard
- PHP Code Sniffer (phpcs.xml)