gpt4 book ai didi

mysql - Sequelizejs 中的外键始终为空

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

我的模型:

module.exports = function(sequelize, DataTypes){
var Podcast = sequelize.define('Podcast', {
id: { type: DataTypes.INTEGER, primaryKey: true,autoIncrement: true},
title: DataTypes.STRING(400),
description: DataTypes.STRING(2000),
img: DataTypes.STRING,
feed: {type: DataTypes.STRING, unique: true},
home: DataTypes.STRING
})
return Podcast;
}

module.exports = function(sequelize, DataTypes){
var PodcastEntry = sequelize.define('PodcastEntry', {
id: { type: DataTypes.INTEGER, primaryKey: true,autoIncrement: true},
title: DataTypes.STRING(400),
summary: DataTypes.STRING(2000),
pubdate: DataTypes.DATE,
guid: {type: DataTypes.STRING(400)},
link: {type: DataTypes.STRING(400)},
length: DataTypes.INTEGER
})
return PodcastEntry;
}

设置关系:

db.Podcast.hasMany(db.PodcastEntry);
db.PodcastEntry.belongsTo(db.Podcast);

插入值:

var Podcast = {};
db.Podcast.findOrCreate({
where: {
title: meta.title,
feed: url
},
defaults: {
description: meta.description,
img: meta.image.url,
home: meta.link
}
})
.spread(function(podcast, created) {
Podcast = podcast;
log.info(podcast.title + " created " + created);
});
while (item = stream.read()) {
db.PodcastEntry.findOrCreate({
where : {
PodcastId: Podcast.id,
guid: item.guid
},
defaults: {
title: item.title,
summary: item.summary,
pubdate: new Date(item.pubdate),
link: item.enclosures[0].url,
length: item.enclosures[0].length,
PodcastId: Podcast.id
}})
.spread(function(podcastEntry, created){
log.info(podcastEntry.title + " created " + created);
});
}

播客条目在我的数据库中创建,但问题是外键“PodcastId”(自动创建)始终为 NULL

我做错了什么?

最佳答案

您将在与创建 Podcast 记录相同的范围内创建 PodcastEntry 记录。因此,在读取流时,Podcast 变量尚未设置为插入的记录。您应该仅在sequelize 完成插入Podcast 记录后才放置创建PodcastEntry 记录的代码。

db.Podcast.findOrCreate({
where: {
title: meta.title,
feed: url
},
defaults: {
description: meta.description,
img: meta.image.url,
home: meta.link
}
})
.spread(function(podcast, created) {
Podcast = podcast;
log.info(podcast.title + " created " + created);

while (item = stream.read()) {
db.PodcastEntry.findOrCreate({
where : {
PodcastId: Podcast.id,
guid: item.guid
},
defaults: {
title: item.title,
summary: item.summary,
pubdate: new Date(item.pubdate),
link: item.enclosures[0].url,
length: item.enclosures[0].length,
PodcastId: Podcast.id
}
})
.spread(function(podcastEntry, created){
log.info(podcastEntry.title + " created " + created);
});
}

});

关于mysql - Sequelizejs 中的外键始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324331/

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