javascript - 使用 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 很陌生。任何建议将不胜感激。
解决方案
你可能需要一些叫做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');
推荐阅读
- python - 在 Python 3 中使用 Zip 每 2 个字符拆分字符串
- compilation - 动态链接和静态链接的指令点值
- javascript - JSON - 将子子项作为 IF 语句的条件
- r - R找到ecdf函数的倒数
- scikit-learn - 为什么我的 train_test_split 不适用于分层选项?
- python - 如何用函数评估方程?
- python - 如何在 Paramiko 服务器中实现端口转发?
- php - 无法在 PHP 中获取 XML 响应
- python - 为什么是负数(MSE 或 MAS)评分参数(如 SKLEARN 中的 neg_mean_absolute_error)被考虑用于回归模型评估
- python - Python Matplotlib:如何禁用约束布局但保持轴位置?