The model class inherited from the Tag
of the blog's frontend.
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.
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}]],
UNLINK_ON_REMOVE: ['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
static findByName (name) {
return this.find({name: new RegExp(`^${name}$`, 'i')});
}
The findBySearch
method finds labels by text.
module/admin/model/Tag.js
static findBySearch (text) {
return text
? this.find(['LIKE', 'name', `%${text}%`])
: this.find();
}
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.
module/admin/model/Tag.js
relArticles () {
return this.hasMany(Article, Article.PK, 'articleId')
.viaTable('rel_article_tag', 'tagId', this.PK)
.removeOnUnlink();
}