您好,我正在使用findOrCreate方法插入记录,但是该方法似乎不适用于包含关联。如果数据库中存在include关联,则会出现错误 使用以下输入。
无法读取未定义的属性“字段”
首次尝试(成功,关系也在“通过”表中创建)
[
{
"album_type": "compilation",
"id": "21132268",
"name": "Album One",
"authors": [
{
"name": "Node Js",
"suffix": "Dr."
}
]
}
]
第二次尝试失败(拥有一个新相册,但作者相同)
[
{
"album_type": "compilation",
"id": "23398868",
"name": "Album Two",
"authors": [
{
"name": "Node Js",
"suffix": "Dr."
}
]
}
]
错误:
“无法读取未定义的属性'field'”,.......“ TypeError:无法 在以下位置读取未定义的属性“字段” options.defaults.Object.keys.map.name ...........
这是DB Functon
var createAlbum = async (albums) => {
try {
// transaction handle
return await models.sequelize.transaction (t => {
// Prepare each album to be created
return Promise.all(albums.map(album => {
return models.Album.findOrCreate({
transaction: t,
where: {name: album.name}, // where: {id: album.id}
defaults: album,
include: ['authors']
})
}))
});
} catch (error) {
// transaction will be rolled back if error
logger.error(error);
throw error;
}
}
模型
//album.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Album = sequelize.define('Album', {
id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false },
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false },
album_type: { type: DataTypes.STRING, allowNull: false },
});
Album.associate = (models) => {
models.Album.belongsToMany(models.Author, {
through: 'AlbumAuthor',
as: 'authors',
foreignKey: 'album_id',
otherKey: 'author_name'
})
}
return Album;
}
//author.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Author = sequelize.define('Author', {
name: { type: DataTypes.STRING, primaryKey: true, allowNull: false },
suffix: { type: DataTypes.STRING, allowNull: true }
});
return Author;
}
//album_author.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var AlbumAuthor = sequelize.define('AlbumAuthor', {
album_id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false },
author_name: { type: DataTypes.STRING, primaryKey: true, allowNull: false }
});
AlbumAuthor.associate = (models) => {
models.AlbumAuthor.belongsTo(models.Album, {
onDelete: 'CASCADE',
foreignKey: 'album_id',
targetKey: 'id',
}),
models.AlbumAuthor.belongsTo(models.Author, {
onDelete: 'CASCADE',
foreignKey: 'author_name',
targetKey: 'name'
})
}
return AlbumAuthor;
}