Tag model

The model class inherited from the Tag of blog frontend.

Tag model

The filter rule changes the value of attribute using a handler. The trim handler removes empty characters at the beginning and at the end of a tag name. Rules are applied in order. Thus the rules that follow the filter will get a modified attribute.

The UNLINK_ON_DELETE constant contains links that need to be broken when deleting a tag model. Otherwise, a link attribute will keep a reference to a non-existent object.

module/admin/model/Tag.js

const Base = require('../../../model/Tag');

module.exports = class Tag extends Base {

  static getConstants () {
    return {
      RULES: [
        ['name', 'required'],
        ['name', 'filter', {filter: 'trim'}],
        ['name', 'string', {min: 2, max: 32}],
        ['name', 'unique', {ignoreCase: true}]
      ],
      INDEXES: [[{name: 1}, {unique: true}]],
      DELETE_ON_UNLINK: ['articles']
    };
  }
};
module.exports.init(module);

const Article = require('./Article');

The findByName method performs case-insensitive search by tag's name.

module/admin/model/Tag.js

findByName (name) {
  return this.find({name: new RegExp(`^${name}$`, 'i')});
}

The findBySearch method finds tags by text.

module/admin/model/Tag.js

findBySearch (text) {
  return text
    ? this.find(['LIKE', 'name', `%${text}%`])
    : this.find();
}

The relArticles relation defines articles that are associated with tag. It overrides a parent method, because here the relation uses a model of the admin module.

The last argument of the hasMany function required to remove a link record after unlink the Article, Tag models. In this case, the record is deleted from the rel_article_tag junction table.

module/admin/model/Tag.js

relArticles () {
  return this.hasMany(Article, Article.PK, 'articleId').viaTable('rel_article_tag', 'tagId', this.PK);
}