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.


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']

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

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


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

The findBySearch method finds tags by text.


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.


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