我正在尝试使用 Sails 构建一个类似亚马逊的产品类别和子类别层次结构.js。
我从多对多关系开始,到目前为止,我已经能够实现一半。到目前为止,我的工作是类别,类别有与之链接的产品,下面是它的实例:
电脑配件 -> 蓝宝石 RX 580, 蓝宝石 5700XT, 海盗船 550W 电源
以下是多对多关系模型的外观:
// 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'
}
}
};
我想从中构建的是将子类别设置为类别,下面是它的实例:
电脑配件 -> 显卡 ->蓝宝石 RX 580、蓝宝石 5700XT
电脑配件 -> 电源 -> 海盗船 550W PSU
我对 JavaScript 和 Sails 很陌生。任何建议将不胜感激。
您可能需要称为"反射关联"的东西,然后您可以在类别模型中包含类似的东西:
// 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');