gpt4 book ai didi

javascript - 从 SequelizeJS 中的表中选择特定属性

转载 作者:行者123 更新时间:2023-11-30 22:21:56 24 4
gpt4 key购买 nike

那些是我的表(不包括所有列)和关系

var client = schema.define('client', {
name: {
type: Sequelize.STRING,
allowNull: false
},
}

var task = schema.define('task', {
name: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
description: {
type: Sequelize.STRING,
}
}

var clientTask = schema.define('clientTask', {
value: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: false
},
}

client.belongsToMany(task, { through: clientTask });
task.belongsToMany(client, { through: clientTask });

我只想从任务中获取 name 并从 clientTask 中获取 value,我通过客户端 ID 搜索,这是我目前尝试的方法。

client.findAll({ 
attributes: [],
where: {id: clientId},
include: [{
model: task,
attributes: ['name']
}]
}).then(function (clients) {
//client.tasks is array with task objects(models) with only name attribute
//client.tasks[0].clientTask is object(models) with all attributes but I want only `value`
}

基本上我想要的是这个查询

Select
tasks.name,
clienttasks.value
From
clients Inner Join
clienttasks
On clienttasks.clientId = clients.id Inner Join
tasks
On clienttasks.taskId = tasks.id
Where clients.id = ?

最佳答案

你可以这样查询

clients.findById(1, {
attributes: ['id'],
include: [{
model: tasks,
attributes: ['name'],
required: false
}]
}).then(function(client) {
return client.tasks.map(function(task) {
return {
name: task.name,
value: task.clients_tasks.value
};
});
}).then(function(result) {
console.log(result);
// The rest of you logic here...
});

关于javascript - 从 SequelizeJS 中的表中选择特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439254/

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