gpt4 book ai didi

sequelize.js - Sequelize ORM - 如何使模型具有始终处于特定持久顺序的对象数组

转载 作者:行者123 更新时间:2023-12-03 22:23:19 25 4
gpt4 key购买 nike

我正在尝试制作一个包含一系列项目的 Sequelize 模型(如下所示):

{
id:1,
name: Name,
hobbies: [
'hobby one',
'hobby two',
'hobby three',
'hobby four',
]
}

我还需要确保数组中的项目按特定顺序排列

最佳答案

关系示例

// Define Users
const Users = sequelize.define('User', {
id: {type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true},
name: {type: DataTypes.STRING},
});

// Define Hobbies
const UserHobbies = sequelize.define('UserHobbie', {
id: {type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true},
name: {type: DataTypes.STRING},
}, {timestamps: true});

// Add Asocciation
Users.hasMany(UserHobbies, {
as: 'hobbies',
onDelete: 'cascade',
});

// Create scope 'withhobbies'
Users.addScope('withhobbies', {
include: [{ // Add join to hobbies
model: UserHobbies,
as: 'hobbies',
attributes: ['name'],
orderBy: [ // Order by hobbie creation time (autogenerate by option timestamps: true)
['createdAt', 'ASC'],
],
}],
});

// Use method to make final object
async function getUsersAndHobbies() {
const users = await Users.scope('withhobbies').findAll(); // Use scope to include hobbies
return users.map((u) => {
const plain = u.get({plain: true}); // Get plain object
return {
...plain,
hobbies: plain.hobbies.map((h) => h.name), // override hobbies with only the names
});
};

使用 setter 和 Getter 的示例:
// Define Users
const Users = sequelize.define('User', {
id: {type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true},
name: {type: DataTypes.STRING},
defaultValue: '[]',
hobbies: {
type: DataTypes.TEXT,
get() {
return JSON.parse(this.getDataValue('hobbies'));
},
set(val) {
if (!Array.isArray(val)) {
throw new Error('hobbies must to be an array');
}
this.setDataValue('hobbies', JSON.stringify(val));
},
},
});

关于sequelize.js - Sequelize ORM - 如何使模型具有始终处于特定持久顺序的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60412210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com