https://github.com/rkit/tags-behavior-yii2
Tags Behavior for Yii2
https://github.com/rkit/tags-behavior-yii2
tags yii2
Last synced: 5 months ago
JSON representation
Tags Behavior for Yii2
- Host: GitHub
- URL: https://github.com/rkit/tags-behavior-yii2
- Owner: rkit
- License: mit
- Created: 2018-07-12T15:58:15.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-08-07T16:19:27.000Z (almost 8 years ago)
- Last Synced: 2024-04-19T06:44:22.070Z (about 2 years ago)
- Topics: tags, yii2
- Language: PHP
- Size: 25.4 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Tags Behavior for Yii2
[](https://travis-ci.org/rkit/tags-behavior-yii2)
[](https://scrutinizer-ci.com/g/rkit/tags-behavior-yii2/?branch=master)
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.
1. Add `tag` and `post_to_tag` tables and a `Tag` model for the tags
```php
$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']);
```
2. Add a `TagsBehavior` behavior to the `Post` model
```php
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;
},
],
];
}
```
3. Add a `tags` relation (see `relation` option in the behavior)
```php
/**
* @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
```php
$model = new Post();
$model->setTagValues(['example1', 'example2']);
$model->save();
```
### Get tags
```php
$post = Post::find()->with('tags')->where(['id' => $id])->one();
$post->getTagValues();
```
### Remove tags
```php
$model = new Post();
$model->setTagValues([]);
$model->save();
```
## Tests
- [See docs](/tests/#tests)
## Coding Standard
- PHP Code Sniffer ([phpcs.xml](./phpcs.xml))