首页 > 解决方案 > 使用 Sails.js 的类别和子类别产品层次结构

问题描述

我正在尝试使用 Sails.js 构建类似亚马逊的产品类别和子类别层次结构。

我从多对多关系开始,到目前为止,我已经能够实现其中的一半。到目前为止,我正在工作的是类别,类别有与之相关的产品,下面是它的一个实例:

电脑配件 -> Sapphire RX 580, Sapphire 5700XT, Corsair 550W PSU

下面是多对多关系模型的样子:

    // Product.js
    
    module.exports = {
    
      attributes: {
    
        name: {
          type: 'string',
          required: true,
          unique: true,
          allowNull: false
        },
        keywords: {
          type: 'json',
          required: false
        },
        
        // Reference to Category
        category: {
          collection: 'category',
          via: 'product'
        },
    
      },
    }; 

   // Category.js

    module.exports = {
    
        attributes: {
            name: {
          type: 'string',
          required: true,
          unique: true
        },
        // Reference to Product
        product: {
          collection: 'product',
          via: 'category'
        }
      }
      
    };

我想以此为基础建立子类别,下面是它的一个实例:

电脑配件 -> 显卡 -> Sapphire RX 580, Sapphire 5700XT

电脑配件 -> 电源 -> Corsair 550W PSU

我对 JavaScript 和 Sails 很陌生。任何建议将不胜感激。

标签: javascriptnode.jsmongodbsails.js

解决方案


你可能需要一些叫做Reflexive Association的东西,然后你可以在Category模型中包含类似的东西:

// api/models/Category.js

parent: {
  model: 'category'
}

children: {
  collection: 'category',
  via: 'parent'
}

如果您需要保存值:

const parentId = 1;
await Category.addToCollection(parentId, 'children').members([2, 3, 4]);

然后当您需要填充关系字段时:

const categories = await Category.find().populate('children');

推荐阅读