Build a blog with Areto Node.js framework

Tag model

The model class inherited from the Tag of the blog's frontend.

Tag model

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

The UNLINK_ON_REMOVE constant contains links that need to be broken when removing a label model. Otherwise, the link attribute will keep a reference to a non-existent object.

modules/admin/models/Tag.js

'use strict';
const Base = require('../../../models/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}]
      ],            
      UNLINK_ON_REMOVE: ['articles']
    };
  }
};
module.exports.init(module);       
const Article = require('./Article');

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

modules/admin/models/Tag.js

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

The findBySearch method finds labels by text.

modules/admin/models/Tag.js

...
static findBySearch (text) {
  let query = this.find();
  if (text) {
    query.where(['LIKE', 'name', `%${text}%`]);
  }
  return query;
}
...

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

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

modules/admin/models/Tag.js

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