gpt4 book ai didi

mysql - SequelizeEagerLoadingError : associated not working in sequelize

转载 作者:行者123 更新时间:2023-12-03 22:20:48 28 4
gpt4 key购买 nike

我有两个表,父表是 checkout_product,它的子表是 product_attributes
现在我正在两个表之间创建关联,因此出现错误:
这是我的代码

const Sequelize = require('sequelize');
const { checkout_product_view } = require('../controller/checkoutProductController');
const sequelize = new Sequelize('celeb', 'root', '', {
host: 'localhost',
dialect: 'mysql' ,
});

var Checkout_product = sequelize.define('checkout_products',{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING
},
price : {
type : Sequelize.STRING
},
image : {
type: Sequelize.STRING
},
quantity : {
type: Sequelize.STRING
},


});
Checkout_product.associate = function(models) {
checkout_products.hasMany(models.Product_attributes, {
foreignKey: 'product_id',
});
};


sequelize.sync()
.catch(error => console.log('This error occured', error));



module.exports = Checkout_product;
这是我的 product_attributes 模型:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('celeb', 'root', '', {
host: 'localhost',
dialect: 'mysql' ,
});

var Product_attribute = sequelize.define('product_attribute',{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
product_id: {
type: Sequelize.INTEGER
},
attribute_name : {
type : Sequelize.STRING
},
attribute : {
type : Sequelize.STRING
},
price : {
type : Sequelize.STRING
}

});

Product_attribute.associate = (models) => {
Product_attribute.belongsTo(models.Checkout_product, {
foreign_key: 'product_id',
sourceKey: 'id'
});
};


sequelize.sync()
.then(() => console.log('Product_attribute'))
.catch(error => console.log('This error occured', error));



module.exports = Product_attribute;
产品有很多 product_attributes 所以每当我调用以下函数时都会收到此错误:
module.exports.checkout_product_get = function (req, res) {
Checkout_product.findAll({
include: [ {
model : Product_attributes
}]
})
.then(checkout_product => {
console.log(checkout_product),
res.json(checkout_product)
})
}
错误:UnhandledPromiseRejectionWarning:SequelizeEagerLoadingError:product_attribute 与 checkout_products 无关!

最佳答案

您没有为所有注册的模型调用 associate 方法。
我建议您像我在这个 answer 中描述的那样定义和注册所有模型和关联

关于mysql - SequelizeEagerLoadingError : associated not working in sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65211302/

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