Hi I am new to Sequelize the hasOne association is not working for me I am trying to make two tables a table of
- Dealer containing a dealer's name and description
- DealerProducts containing the Dealers products and prices as well as the table1 as the FKEY (which I want hasOne to make for me the FKEY)
So I'm making 3 files one for each of them and then an index.js file to gather them in and make their relevant association
Here are those files:
dealer-model.js
module.exports = (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const Dealer = sequelize.define('Dealer', {
did: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: [1, 50]
}
},
description: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
tableName: 'dealers',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
// paranoid: true
})
return Dealer;
}
dealer-products-model.js
module.exports = (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const DealerProduct = sequelize.define('DealerProduct', {
dpid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
product_name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: [1, 100]
}
},
type: {
type: DataTypes.STRING,
allowNull: true,
validate: {
len: [1, 100]
}
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
price: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
tableName: 'dealer_products',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
// paranoid: true
})
return DealerProduct;
}
Then the index.js
module.exports = async (sequelize = require('../db')) => {
const { DataTypes } = require('sequelize');
const User = require('./user-model');
const Dealer = require('./dealers-model');
const DealerProduct = require('./dealer-products-model');
User(sequelize)
Dealer(sequelize)
DealerProduct(sequelize)
DealerProduct.hasOne(Dealer, {
foreignKey: {
type: DataTypes.UUID,
allowNull: false,
name: "dealers_did"
}
});
Dealer.belongsTo(DealerProduct);
sequelize.sync({alter: true}); //force: true
}
This is making the tables for my postgres but association is not working as I am not making a FKEY column for the DealerProducts
and this is the error I am getting
TypeError: DealerProduct.hasOne is not a function
Where am I going wrong?
CodePudding user response:
UPDATE
My answer was as simple as saving the Dealer and DealerProduct as variables then using the variables as the hasOne example:
const dealer = Dealer(sequelize)
const dealerProduct = DealerProduct(sequelize)
dealer.hasOne(dealerProduct, {
foreignKey: {
type: DataTypes.UUID,
allowNull: false,
name: "dealers_did"
}
});
dealerProduct.belongsTo(dealer);```
So this worked