I'm getting images is not associated to product! error while binding the association of the model.
ProductImages is associated to Product and ProductImages is associated to Images model. So, i need to render images property into products collection by assigning to it.
The model that i'm trying to bind is as below.
products.model.ts
const Product = SQLize.define('product', {
id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }
product_title: { type: new DataTypes.STRING(255) },
vendor_id: { type: DataTypes.INTEGER }
});
Product.hasMany(ProductImages, {foreignKey: 'product_id', targetKey: 'id', as :'product_img_refs'})
export { Product };
product-images.model.ts
const ProductImages = SQLize.define('product_images', {
id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, },
product_id: { type: DataTypes.INTEGER },
product_image_id: { type: DataTypes.INTEGER }
img_type_id: { type: DataTypes.INTEGER }
});
ProductImages.belongsTo(ImagesModel, {foreignKey: 'product_image_id', targetKey: 'id', as:'product_images' })
export {ProductImages}
images.model.ts:
const ImagesModel = SQLize.define('images', {
id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, },
img_url: { type: DataTypes.STRING }
});
export { ImagesModel }
Below is the repository file on which i have performed the SQLize operation.
public async getProductData() {
var prodData = Product.findAll({
include: [
{ model: Vendor, as: 'vendor' },
{ model: ProductImages, as: 'product_img_refs' }
{ model: ImagesModel, as: 'product_images' }
]
});
return prodData;
}
=> Sample product_images table records.
=> Sample images table records.
=> DB Schema for more visualisation.
=> I have checked this answer but it is not relevant to my model as i have three models with different association.
Instead of both a hasMany and a belongsTo relationship, create a many-to-many relationship on Product to Images and also one from Images to Product.
You can extend the auto-generated table (with ProductId and ImageId columns) by passing the name of a model.
const ProductImages = SQLize.define('ProductImages', {
// ...
});
Product.belongsToMany(ImagesModel, { through: ProductImages });
ImagesModel.belongsToMany(Product, { through: ProductImages });
You can now do:
await Product.getImages();
await Images.getProducts();
Or use the include option while querying. There are examples in the documentation here. It'll be something like:
await Product.findAll({
include: ImagesModel,
});
// It will be nested as such:
// {
// fields from product
// Images: {
// fields from image
// ProductImages: {
// fields from the 'through' table
// }
// }
// }
Related
I'm trying to bulk insert with associations,
I have this 'Song' model which have one to many relationships with 'Genre' and 'Language' defined with the migrations CLI.
Song:
module.exports = (sequelize, DataTypes) => {
class Song extends Model {
static associate(models) {
// define association here
Song.hasMany(models["Language"])
Song.hasMany(models["Genre"])
}
};
Song.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING,
energy: {type: DataTypes.FLOAT, allowNull: false},
valence: {type: DataTypes.FLOAT, allowNull: false}
}, {
sequelize,
modelName: 'Song',
timestamps: true
});
return Song;
};
Language:
module.exports = (sequelize, DataTypes) => {
class Language extends Model {
static associate(models) {
// define association here
models["Language"].belongsTo(models["Song"])
}
};
Language.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING
}, {
sequelize,
modelName: 'Language',
indexes: [{unique: true, fields: ['name']}]
});
return Language;
};
Genre:
module.exports = (sequelize, DataTypes) => {
class Genre extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
models["Genre"].belongsTo(models["Song"])
}
};
Genre.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: DataTypes.STRING
}, {
sequelize,
modelName: 'Genre',
indexes: [{unique: true, fields: ['name']}]
});
return Genre;
};
I'm trying to bulk insert songs with languages and genres like this:
Song.bulkCreate(songs, {
include: [Genre,Language]
}).then(() => {
const result = {
status: "ok",
message: "Upload Successfully!",
}
res.json(result);
});
each song in the songs array is structured like this:
{
name: "abc",
genres: [{name: "abc"}],
languages: [{name: "English"}],
energy: 1,
valence: 1
}
I'm ending up with a full songs table but genres and languages are empty
What am I doing wrong?
Thanks.
Just in case anyone else got here from a search, starting from version 5.14
Sequelize added the option to use include option in bulkCreate as follows:
await Song.bulkCreate(songsRecordsToCreate, {
include: [Genre,Language]
})
Edit 2nd Feb 2023
As none answered above, as of v5.14.0 the include option is now available on bulkInsert.
Unfortunately bulkCreate does not support include option like create do.
You should use create in a cycle inside a transaction.
const transaction = ...
for (const song of songs) {
await Song.create(song, {
include: [Genre,Language]
}, { transaction })
}
await transaction.commit()
or you can use Promise.all to avoid using for.
I have three tables (all associated model classnames use PascalCase)
schools school_codes course
------ ------ ------
id (pk) code (pk) name
name school_id (fk) school_code (fk)
I'm trying to define sequelize relations, so that this Course lookup returns the associated School:
const courseWithSchool = await models.Course.findOne({
include: [{
model: models.School,
required: true,
}],
})
The mysql for this is very simple.
mysql> select c.*, s.* from courses c inner join school_codes sc on c.school_code = sc.code inner join schools s on s.id = sc.school_id;
How do I define the relations in sequelize models (without modifying existing schema)? Thanks!
Here are the model definitions I have:
schools.js
module.exports = (sequelize, DataTypes) => {
const School = sequelize.define('School', {
name: DataTypes.STRING,
}, { underscored: true, freezeTableName: true, tableName: 'schools' })
return School
}
course.js
module.exports = (sequelize, DataTypes) => {
const Course = sequelize.define('Course', {
id: {
type: DataTypes.STRING,
primaryKey: true,
},
name: DataTypes.STRING,
school_code: {
type: DataTypes.STRING,
references: {
model: 'school_codes',
key: 'code',
}
}
}, { underscored: true, freezeTableName: true, tableName: 'courses' })
return Course
}
schoolcode.js
module.exports = (sequelize, DataTypes) => {
const SchoolCode = sequelize.define('SchoolCode', {
code:{
type: DataTypes.STRING,
primaryKey: true,
references: {
model: 'courses',
key: 'school_code'
}
},
school_id: {
type: DataTypes.INTEGER,
references: {
model: 'schools',
key: 'id',
},
},
}, { underscored: true, freezeTableName: true, tableName: 'school_codes', })
return SchoolCode
}
I'm just looking for the relations to add to the bottom of each model definition - example...
// School.associate = function (models) {
// School.belongsToMany(models.Course, {
// through: 'school_codes',
// foreignKey: 'school_id',
// otherKey: 'code'
// })
// }
We can keep association in its respective model. I prefer to keep association in respective master table rather than mapping table. The idea is to associate source model to target model and its relationship in both direction. For example let us say source model School has one SchoolCode target model and its reverse relation
//school.model.js
module.exports = (sequelize, DataTypes) => {
const School = sequelize.define('school', {
name: DataTypes.STRING,
}, { underscored: true, freezeTableName: true, tableName: 'schools' })
School.associate = function ({SchoolCode, Course}) {
School.hasOne(SchoolCode, {
foreignKey: 'school_id',
})
SchoolCode.belongsTo(School, {foreignKey: 'school_id'})
School.belongsToMany(Course, { through: SchoolCode , foreignKey : 'school_id'}); //added new
}
return School;
}
//course.model.js
module.exports = (sequelize, DataTypes) => {
const Course = sequelize.define('course', {
id: {
type: DataTypes.STRING,
primaryKey: true,
},
name: DataTypes.STRING,
school_code: {
type: DataTypes.STRING,
references: {
model: 'school_codes',
key: 'code',
}
}
}, { underscored: true, freezeTableName: true, tableName: 'courses' })
Course.associate = function ({SchoolCode, School}) {
Course.hasMany(SchoolCode, {
foreignKey: 'code',
})
Course.belongsToMany(School, { through: SchoolCode, foreignKey : 'code'}); //added new
}
return Course;
}
Finally the third model of SchoolCode (Mapping table).
Note that we don't have to add a reference school_code. It is a primaryKey code of same table. We use references mainly to define the foreign keys, no need for reverse definition here.
Hence commented that part from code below.
module.exports = (sequelize, DataTypes) => {
const SchoolCode = sequelize.define('SchoolCode', {
code:{
type: DataTypes.STRING,
primaryKey: true,
// references: {
// model: 'courses',
// key: 'school_code'
// }
},
school_id: {
type: DataTypes.INTEGER,
references: {
model: 'school',
key: 'id',
},
},
}, { underscored: true, freezeTableName: true, tableName: 'school_codes', })
return SchoolCode
}
References : https://sequelize.org/master/manual/assocs.html
You can define relations like
SchoolCode.belongsTo(School, { foreignKey: 'school_id', targetKey: 'id' });
Course.belongsTo(SchoolCode, { foreignKey: 'school_code', targetKey: 'code' });
I have a a model called Post and Country. When I filter by a particular country Id, it returns correctly filtered posts but only returns that specific country in the response and discards all the other countries associated with the Post. How can I include and retain all the countries associated with the post in the response?
Post.js
class Post extends Sequelize.Model {
static init(sequelize, DataTypes) {
return super.init(
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
number: {
type: Sequelize.INTEGER,
validate: {
isInt: true
}
},
}
);
static associate(models) {
this.myAssociation = this.belongsToMany(models.Country,
{through: "CountriesImpacted", foreignKey: "id"});
}
}
module.exports = Incident;
Country.js
class Country extends Sequelize.Model {
static init(sequelize, DataTypes) {
return super.init(
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING,
primaryKey: true,
unique: true
}
}, {sequelize, modelName: 'country', tableName: 'Countries'}
)
}
}
module.exports = Country;
routes.js
Post.findAndCountAll({
attributes: { exclude: ["createdAt", "updatedAt"] },
order: [Country, "name", "asc"],
include: [{
model: Country,
where: { id: country_ids_from_request }
}],
where: filters,
distinct: true,
offset: offset,
limit: limit
})
example output
{
'0': {
id: 1,
number: 1203021,
countries: [
{
id: 6,
name: 'Australia',
CountriesImpacted: {
id: 1,
countryId: 6
}
},
{
id: 7,
name: 'New Zealand',
CountriesImpacted: {
id: 1,
countryId: 7
}
}
]
}
}
when I filter by country id 6, the repsonse will discard New Zealand...
It requires a sub-query to fetch the eligible Post model. It will look like following
return Post.findAll({
include: [
{
model: Country
}
],
where: {
id : {
[Sequelize.Op.in] : [Sequelize.literal(`(SELECT posts.id FROM posts INNER JOIN countries ON countries.postId = posts.id WHERE ${COUNTRY_ID} IN (countries.id))`)] // Subquery...
}
}
})
Here i assume following
Your Post schema name is posts.
Your Country schema name is countries.
Country has a postsId foreign key REFERENCES TO Post.
If you are not comfortable with having sub-query inside your project while using Sequelize (ORM), then you have to execute two query, first fetching all the eligible Posts then fetch desired for those Posts.
I have a postrgresql/Sequelize model called Segment, which belongs to many models:
module.exports = (sequelize, DataTypes) => {
const Segment = sequelize.define(
'segment',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
provider_id: {
type: DataTypes.INTEGER,
references: {
model: 'provider',
key: 'id'
}
},
summary_id: {
type: DataTypes.INTEGER,
references: {
model: 'summary',
key: 'id'
}
},
audience_id: {
type: DataTypes.INTEGER,
references: {
model: 'audience',
key: 'id'
}
},
onboarding_id: {
type: DataTypes.INTEGER,
references: {
model: 'onboarding',
key: 'id'
}
}
},
{
// disable the modification of table names; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,
tableName: 'segment'
}
);
Segment.associate = models => {
Segment.belongsTo(models.Provider, { foreignKey: 'id' });
Segment.belongsTo(models.Summary, { foreignKey: 'id' });
Segment.belongsTo(models.Audience, { foreignKey: 'id' });
Segment.belongsTo(models.Onboarding, { foreignKey: 'id' });
};
return Segment;
};
The models that segment has associations to (ie provider_id, summary_id, audience_id, onboarding_id) look like this:
Provider:
module.exports = (sequelize, DataTypes) => {
const Provider = sequelize.define(
'provider',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
providerName: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING
},
privacyPolicy: {
type: DataTypes.STRING
}
},
{
freezeTableName: true,
tableName: 'provider'
}
);
Provider.associate = models => {
Provider.hasMany(models.Segment, { foreignKey: 'provider_id' });
};
return Provider;
};
Summary:
module.exports = (sequelize, DataTypes) => {
const Summary = sequelize.define(
'summary',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
summaryName: DataTypes.STRING,
standardIdName: DataTypes.STRING,
description: DataTypes.STRING,
},
{
freezeTableName: true,
tableName: 'summary'
}
);
Summary.associate = models => {
Summary.hasMany(models.Segment, { foreignKey: 'summary_id' });
};
return Summary;
};
Audience:
module.exports = (sequelize, DataTypes) => {
const Audience = sequelize.define(
'audience',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
refreshCadence: DataTypes.STRING,
sourceLookbackWindow: DataTypes.STRING
},
{
freezeTableName: true,
tableName: 'audience'
}
);
Audience.associate = models => {
Audience.hasMany(models.Segment, { foreignKey: 'audience_id' });
};
return Audience;
};
Onboarding:
module.exports = (sequelize, DataTypes) => {
const Onboarding = sequelize.define(
'onboarding',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
onboardingExpansions: DataTypes.STRING,
onboardingAudiencePrecision: DataTypes.STRING
},
{
freezeTableName: true,
tableName: 'onboarding'
}
);
Onboarding.associate = models => {
Onboarding.hasMany(models.Segment, { foreignKey: 'onboarding_id' });
};
return Onboarding;
};
My question is: what should come first when creating and saving a Segment record? Do I create and save each one of the other models first (provider, summary, audience, onboarding), and then create/save a Segment with references to those ids? I don't really know what the order of events should be in this situation. Any help is much appreciated! Thanks!
TLDR:
In order to create an instance of Segment, you must have all 4 foreign keys reference exist records on the referenced tables(provider, summary, audience and onboarding).
Explanation:
provider, summary, audience and onboarding tables are independent.
However, Segment model is not independent.
Segment model has 4 columns which are foreign keys.
From PostgresSql Tutorial:
A foreign key is a field or group of fields in a table that uniquely
identifies a row in another table. In other words, a foreign key is
defined in a table that references to the primary key of the other
table.
The table that contains the foreign key is called referencing table or
child table. And the table to which the foreign key references is
called referenced table or parent table.
It means that a foreign key is a constraint that the column should reference the primary key of the referenced table.
So, you must create all the resources of a created row of Segment.
I'm new to Sequelize and trying to test if an n:m association I set up between two models, User and Podcast, is working. When I try to run this query, I get some kind of DB error that isn't specific about what's wrong:
User.findOne({
where: { id: id },
include: [{ model: Podcast }]
});
Does anyone know what I'm messing up? I suspect there's something wrong in how I've set up the association, like I'm referencing the names of tables slightly incorrectly, but the migration to create the association worked.
Here's my User.js model file:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
photo: {
type: DataTypes.STRING
}
});
User.associate = function(models) {
// associations can be defined here
User.belongsToMany(models.Podcast, {
through: 'user_podcast'
});
};
return User;
};
And here's my Podcast.js file:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Podcast = sequelize.define('Podcast', {
id: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false
},
title: {
type: DataTypes.STRING,
allowNull: false
},
thumbnail: {
type: DataTypes.STRING
},
website: {
type: DataTypes.STRING
}
});
Podcast.associate = function(models) {
// associations can be defined here
Podcast.belongsToMany(models.User, {
through: 'user_podcast'
});
};
return Podcast;
};
And here's the migration I ran to join the two tables:
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('user_podcast', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
userId: {
type: Sequelize.INTEGER,
references: {
model: 'Users',
key: 'id'
}
},
podcastId: {
type: Sequelize.STRING,
references: {
model: 'Podcasts',
key: 'id'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('user_podcast');
}
};
And here's the project on Github for further reference:
https://github.com/olliebeannn/chatterpod
You don't need to create a migration for the M:N table. Now you have something wrong on your user_podcast model. If you are setting a M:N relation between to tables your primary key will be the combination between the foreign key from these two models. If you still want a single id primary key for your table, then you won't use belongsToMany instead use hasMany on user and podcast models pointing to a new model user_podcast.
As far as I see on your first query, it seems that you really need a M:N relation so you can define the model as you do with user and podcast like this:
module.exports = (sequelize, DataTypes) => {
const UserPodcast = sequelize.define('user_podcast', {
userId: {
// field: 'user_id', #Use 'field' attribute is you have to match a different format name on the db
type: DataTypes.INTEGER
},
podcastId: {
// field: 'podcast_id',
type: DataTypes.INTEGER
},
});
UserPodcast.associate = function(models) {
models.User.belongsToMany(models.Podcast, {
as: 'podcasts', //this is very important
through: { model: UserPodcast },
// foreignKey: 'user_id'
});
models.Podcast.belongsToMany(models.User, {
as: 'users',
through: { model: UserPodcast },
// foreignKey: 'podcast_id'
});
};
return UserPodcast;
};
I do prefer to have the belongsToMany associations on the save function where I define the join model, and you have to notice that I used as: attribute on the association. This is very important because this will help sequelize to know which association are you referring on the query.
User.findOne({
where: { id: id },
include: [{
model: Podcast,
as: 'podcasts' //here I use the previous alias
}]
});