rkit/tags-behavior-yii2

Yii2 的标签行为

安装: 6

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 3

分支: 0

开放问题: 0

类型:yii2-extension

1.0.0 2018-07-16 16:57 UTC

This package is not auto-updated.

Last update: 2024-09-23 08:02:28 UTC


README

Build Status Scrutinizer Code Quality

灵活的 Yii2 标签行为。

需求

PHP 7

安装

composer require rkit/tags-behavior-yii2

配置

例如,我们有一个 Post 模型,我们想添加标签。
让我们来做。

  1. 添加 tagpost_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']);
  1. 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;
            },
        ],
    ];
}
  1. 添加一个 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();

测试

编码规范