【问题标题】:Categories and subcategories product hierarchy with Sails.js使用 Sails.js 的类别和子类别产品层次结构
【发布时间】:2020-10-20 12:51:23
【问题描述】:

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

我从many-to-many relation 开始,到目前为止,我已经完成了一半。到现在为止我工作的是类别,类别有与之关联的产品,下面是它的一个实例:

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

many-to-many relation 模型如下所示:

    // 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 还是很陌生。任何建议将不胜感激。

【问题讨论】:

    标签: javascript node.js mongodb sails.js


    【解决方案1】:

    你可能需要一个叫做 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');
    

    【讨论】:

    • 这正是我在阅读后发现的。这应该是正确的答案,我试一试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多