kamikaza007
kamikaza007

Reputation: 33

yii2 and select2 for tags

I'm using kartik select2 widget like this:

echo Select2::widget([
        'model' => $model,
        'attribute' => 'script_tags',
        'data' => $model->tagList,
        'options' => ['multiple' => true,'placeholder' => 'Select states ...'],
        'pluginOptions' => [
            'tags' => true
        ],
    ]);

$model->tagList is array in this format ['id'=>'name'] populated from database.

My question is what is the best why to save it into db table because with custom tags i have response for script_tags like this

[0=>'1', 1=>'5', 2=>'math'],

i need to save new tag in table tag[fields=id, name] and relations for all tags in table tagmap[fields=id, script_id, tag_id]

should i check if is integer save relations in tagmap, if is string save first new tag in tag table then save relation in tagmap

Upvotes: 2

Views: 812

Answers (1)

Beowulfenator
Beowulfenator

Reputation: 2300

Your approach looks fine, except when somebody explicitly enters a number as tag value. Let's imagine in your tag table ID 1 is 'foo' and ID 5 is 'bar'. There's no way to tell if you got a 'foo,bar,math' or 'foo,5,math'. You could check if those IDs actually exist in your database and act accordingly, but that's probably overkill.

However, I suggest you take a look at some tagging solutions that already exist. I'm pretty happy with 2amigos/yii2-taggable-behavior, but there's also creocoder/yii2-taggable and probably many others.

As an added benefit, 2amigos taggable also stores tag frequencies.

Keep in mind that having an id column in tagmap, which I bet is an autoincrement PK, is bad practice, you should use (script_id, tag_id) as a composite PK.

Upvotes: 1

Related Questions