Tag model

The Tag class manages the article's thematic labels.

Search for articles by tag

Define a table name, stored attributes and validation rules in the getConstants static method. Tag's validation is required for the values entered by user to search for articles.


const Base = require('areto/db/ActiveRecord');

module.exports = class Tag extends Base {

  static getConstants () {
    return {
      TABLE: 'tag',
      ATTRS: ['name'],
      RULES: [
        ['name', 'required'],
        ['name', 'string', {min:2, max:32}]

  getTitle () {
    return this.get('name');

  // place methods here

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

One tag can refer to several articles, while any article may be associated with lots of tags. This type of relationship is called a "many to many". It was used in the relArticles relation. The rel_article_tag junction table keeps related objects: tag - article.

The rel_article_tag table is not created in model. All changes take place automatically when editing relations in the admin module of blog.

The [Article.PK, 'articleId'] parameter binds article with records in junction table. Also the ['tagId', this.PK] parameter binds records in junction table with a tag. Thus a tag associated with a article.

In the public part of blog, a filter is applied to selection condition by tags. The filter returns only published articles. In addition, specify the requirement to find a Article model with mainPhoto, tags relations. It will be used in the view of article.


relArticles () {
  return this.hasMany(Article, Article.PK, 'articleId')
    .and({status: Article.STATUS_PUBLISHED})
    .with('mainPhoto', 'tags')
    .viaTable('rel_article_tag', 'tagId', this.PK);