gpt4 book ai didi

postgresql - Sequelize - 无法在 1 :N relationship 中保存关联

转载 作者:行者123 更新时间:2023-11-29 12:25:08 25 4
gpt4 key购买 nike

你在做什么?

尝试添加关联并将它们保存到数据库

js

var Device = models.Device;
var Log = models.Log;;

var logs = [
{
"message_level" : 1,
"message" : "test log 1"
},
{
"message_level" : 1,
"message" : "test log 2"
},
{
"message_level" : 1,
"message" : "test log 3"
}
];

var devID = 'X3dE4DEW';

describe('Logs', function() {
it('should create log', function(done) {
Device.create({
"originalID" : devID
}).then(
function() {
return Device.findOne({"where": {originalID: devID},
include: [ { model: Log, as : "Logs" } ] }).then(
function(device) {
if (device) {
logs = logs.map(
function(log) {
return Log.build(log);
}
);
console.log(logs) // is NOT Empty -> OK
return device.addLogs(logs).then(
function(device) {
return device.getLogs().then(
function(logs) {
console.log(logs); // EMPTY [] -> NOT OK
logs.length.should.equal(3);
done();
}
);
}
);
}

return Promise.reject('Not valid Device ID');
}
).catch(function(error){
console.log(error);
done();
});
}
);
});
});

它们是如何定义的

// models
// Device
Device = pg.define('device', {
originalID: {
type: Sequelize.STRING(16) // Up to 16
}
});

// LogRecord
Log = pg.define('log', {
message_level: {
type: Sequelize.INTEGER
},
message: {
type: Sequelize.STRING(100) // Up to 100
}
});
Device.hasMany(Log, { as : "Logs" });
Log.belongsTo(Device);

你期望发生什么?

addLogs 应该将关联项保存到数据库

实际发生了什么?

项目未保存,device.getLogs() 返回一个空数组 []

{ AssertionError: expected 0 to equal 3 }

方言:PG数据库版本: 9.6.1 Sequelize 版本: ~3.30.x

最佳答案

关联行有几种解决方案

  • 如果您使用 add<Association(s)>函数,确保关联的对象已经存储在数据库中。

  • 或者您可以使用 create<Association>创建模型和关联。

    var device;
    Device.create({
    "originalID" : devID
    }).then(function(createdDevice) {
    device = createdDevice;
    return Promise.all(logs.map(log=>{return device.createLog(log);}));
    }).then(function(result) {
    return device.getLogs();
    }).then(function(logs) {
    console.log(logs);
    logs.length.should.equal(3);
    done();
    }).catch(function(error){
    console.log(error);
    done();
    });

    像上面那样使用promises风格,更容易理解,而不是“深入promises”。

关于postgresql - Sequelize - 无法在 1 :N relationship 中保存关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44181830/

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