gpt4 book ai didi

node.js - 关系表不存在

转载 作者:行者123 更新时间:2023-12-03 22:31:32 26 4
gpt4 key购买 nike

我在 sequelize (v6.3.5) 中的 n:m 关系有问题,通常使用此代码我应该自动创建第三个表“Product_File”,但是当我调用 product.addFile(file) 时出现错误“SequelizeDatabaseError:表‘Product_File’不存在”
产品 :

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Product extends Model {
static associate(models) {
this.belongsToMany(models.File, {
through: "Product_File",
});
}
}
Product.init(
{
name: DataTypes.STRING,
description: DataTypes.TEXT,
category_id: DataTypes.INTEGER,
references: DataTypes.STRING,
},
{
sequelize,
modelName: "Product",
}
);
Product.sync().catch((err) => console.error(err));
return Product;
};

文件 :
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class File extends Model {
static associate(models) {
this.belongsToMany(models.Product, {
through: "Product_File",
});
}
}
File.init(
{
name: DataTypes.STRING,
type: DataTypes.STRING,
url: DataTypes.STRING,
},
{
sequelize,
modelName: "File",
}
);
File.sync().catch((err) => console.error(err));
return File;
};

最佳答案

Product_File.js

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Product_File extends Model {
}
Product_File.init({
productId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Products',
key: 'id',
},
},
fileId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Files',
key: 'id',
}
},
}, {
sequelize,
modelName: "Product_File",
});
return Product_File;
};
产品.js
...
this.belongsToMany(models.File, {
foreignKey: 'productId',
otherKey: 'fileId',
through: models.Product_File,
as: 'file'
})
...
测试.js
'use strick';


const Sequelize = require("sequelize");
const Op = Sequelize.Op;
const db = require("../models");

describe('db', () => {

it('Check Product: m:n relationship', async () => {

let A = await db.Product.findAll({
include: ['file'],
});
var aList = JSON.parse(JSON.stringify(A))
console.log(aList)
return
})
})
输出
[
{
id: 1,
name: 'Product 1',
description: null,
category_id: null,
references: null,
createdAt: null,
updatedAt: null,
file: [ [Object] ]
}
]

关于node.js - 关系表不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66495746/

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