rkit / tags-behavior-yii2
Yii2 的标签行为
1.0.0
2018-07-16 16:57 UTC
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-09-23 08:02:28 UTC
README
灵活的 Yii2 标签行为。
需求
PHP 7
安装
composer require rkit/tags-behavior-yii2
配置
例如,我们有一个 Post
模型,我们想添加标签。
让我们来做。
- 添加
tag
和post_to_tag
表以及一个用于标签的Tag
模型
$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']);
- 将
TagsBehavior
行为添加到Post
模型
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; }, ], ]; }
- 添加一个
tags
关联(参见行为中的relation
选项)
/** * @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();
测试
编码规范
- PHP Code Sniffer (phpcs.xml)