I am trying to relate my Users model with the Posts model, what I want to do is that the user when creating a post saves the post id in the 'posteds' field of the user model, but I can't do it
Post Table:
'posteds' shouldn't be there, it should be in the users table
My relationships:
Users.hasMany(Posts, {foreignKey: 'posteds'})
Posts.belongsTo(Users, {foreignKey : 'userId'})
Model User:
import { DataTypes, UUIDV4, Optional, Model} from "sequelize"
import { connection } from "../database"
import { hash, genSalt, compare } from "bcryptjs";
import Posts from "./posts.model";
export const rolesEnum: string[] = ['ADMIN_ROLE', 'MODERATOR_ROLE','USER_ROLE']
interface UserAttributes{
id: number,
email: string,
password: string,
img_url: string,
role: 'ADMIN_ROLE' | 'MODERATOR_ROLE' | 'USER_ROLE',
created_at: Date,
updated_at?: Date
}
interface UserCreationAttributes extends Optional<UserAttributes, "id" | "created_at" | 'img_url'> {}
// We need to declare an interface for our model that is basically what our class would be
interface UserInstance
extends Model<UserAttributes, UserCreationAttributes>,
UserAttributes {}
const Users = connection.define<UserInstance>('users', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: UUIDV4,
unique: true,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
img_url: {
type: DataTypes.STRING,
defaultValue: process.env.DEFAULT_IMAGE || 'default.svg',
allowNull: false
},
role: {
type: DataTypes.STRING,
values: rolesEnum,
defaultValue: 'USER_ROLE',
allowNull: false
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
}
},{
timestamps: false
})
export default Users
Model Posts:
import { DataTypes, Optional, Model, UUIDV4} from "sequelize";
import {connection} from "../database";
interface PostAttributes {
id: number,
title: string,
description: string,
categorys?: Array<string>,
img_url: string,
created_at: Date,
updated_at?: Date,
userId?: string;
}
interface PostCreationAttributes extends Optional<PostAttributes, "id" | "created_at" |"img_url" | "categorys"> {}
// We need to declare an interface for our model that is basically what our class would be
interface PostInstance
extends Model<PostAttributes, PostCreationAttributes>,
PostAttributes {}
const Posts = connection.define<PostInstance>('posts', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: UUIDV4,
unique: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.STRING,
allowNull: false
},
categorys: {
type: DataTypes.ARRAY(DataTypes.ENUM('web-devlopment', 'recent', 'featured')),
values: ['web-devlopment', 'recent', 'featured'] //HELP TO SEND MESSAGES OF ERROR
},
img_url: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: process.env.DEFAULT_IMAGE || 'default.svg'
},
created_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false
},
updated_at: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
},{
timestamps: false
})
export default Posts
I believe the issue is with the hasMany definition. Because there can be many post IDs per user, you want to define the relationship but would not want a posteds column in the users table.
instead of:
Users.hasMany(Posts, {foreignKey: 'posteds'})
have you tried this?
Users.hasMany(Posts, { as: 'posts'})
I referenced this tutorial link, maybe it will be helpful:
https://bezkoder.com/sequelize-associate-one-to-many/
Related
I have a classical many-to-many relationship for users which own assets: assets can be transfered to other users during their life so a window time is recorded in the AssetUser "through table",
adding STARTDATE and ENDDATE attributes.
User Table
const User = sequelize.define('User', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
FIRSTNAME: {
type: DataTypes.STRING,
allowNull: false
},
LASTNAME: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
Asset Table
const Asset = sequelize.define('Asset', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
DESCRIPTION: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
AssetUser Join Table
const AssetUser = sequelize.define('AssetUser', {
id: {
type: DataTypes.INTEGER.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
UserID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: User,
key: 'ID'
}
},
AssetID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Asset,
key: 'ID'
}
},
STARTDATE: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
ENDDATE: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: null
}},{ timestamps: false });
The models are created here:
User.belongsToMany(Asset, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
Asset.belongsToMany(User, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
My problem is that I want to query and find all the results where one asset, owned by one user, during a restricted period. I am not able to query the join-table but only User and Assets tables.
How can I add a "where" condition for the AssetUser table inside my query? How should I insert a STARTDATE and/or ENDDATE condition below?
Asset.findAll({
where: {
DESCRIPTION: 'Personal computer'
},
include: {
model: User,
where: {
FIRSTNAME: 'Marcello'
}
}});
Thanks for your help.
I found the solution
Asset.findAll({ where: { DESCRIPTION: 'Personal computer' }, include: { model: User, through: { where: { FIRSTNAME: 'Marcello' } } }});
So I've been trying to build a medium-clone for a project and therefore, I need to make a 1 : N relation for my "User" and "Article" Tables. But when I add the association Article.belongsTo(User); , I receive an error stating Error: Article.belongsTo called with something that's not a subclass of Sequelize.Model , and any kind of help would be highly appreciated.
Here's my code :
Article.js
const {Sequelize, DataTypes} = require('sequelize');
const db = require('../../config/Database');
const User = require('../User/User');
const Article = db.define('Article', {
slug : {
type: DataTypes.STRING(30),
allowNull: false,
primaryKey: true,
unique: true
},
title : {
type: DataTypes.STRING(50),
allowNull: false
},
description : {
type: DataTypes.STRING(100)
},
body : {
type: DataTypes.STRING
},
createdAt : {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
updatedAt : {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
favorited : {
type : DataTypes.BOOLEAN,
defaultValue: 0
},
favoritesCount : {
type : DataTypes.INTEGER,
defaultValue : 0
}
},{
freezeTableName: true
})
Article.belongsTo(User);
module.exports = Article;
User.js
const {Sequelize,DataTypes} = require('sequelize');
const db = require('../../config/Database');
const Article = require('../Article/Article');
const User = db.define('User', {
email: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
unique: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
bio: {
type: DataTypes.STRING(100),
allowNull: true
},
image: {
type: DataTypes.STRING,
allowNull: true
},
token: {
type: DataTypes.STRING
}
},{
freezeTableName: true
})
User.hasMany(Article);
module.exports = User;
I am using postgres for my database and I am trying to create a rule for each team
Here is my following code in my database:
module.exports = (sequelize, DataTypes) => {
const Team = sequelize.define(
"Team",
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
type: DataTypes.STRING,
mission: DataTypes.STRING,
agreement: DataTypes.STRING,
},
{
tableName: "Teams",
timestamps: true,
indexes: [{ unique: false, fields: ["id", "title"] }],
}
);
So the agreement data type is my rules. Do I need to change it to array and create 4 rules in modal or is there anyways I can do it with string?
i have these 2 models:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('services_prices', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true
},
service_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'services',
key: 'id'
}
},
created_at: {
type: DataTypes.DATE,
allowNull: false
},
limit: {
type: DataTypes.INTEGER(11),
allowNull: true
},
price: {
type: DataTypes.INTEGER(11),
allowNull: true
}
});
};
which is parent of this model: (services_user_prices can override services_prices )
module.exports = function(sequelize, DataTypes) {
return sequelize.define('services_user_prices', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
user_id: {
type: DataTypes.INTEGER(11),
allowNull: true
},
created_at: {
type: DataTypes.DATE,
allowNull: false
},
currency: {
type: DataTypes.STRING(255),
allowNull: true
},
is_active: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
is_trial: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
start_date: {
type: DataTypes.DATE,
allowNull: false
},
end_date: {
type: DataTypes.DATE,
allowNull: true
},
price: {
type: DataTypes.INTEGER(11),
allowNull: true
},
bundle_price_id: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'services_prices',
key: 'id'
}
}
});
};
when trying to join them i get an error:
EagerLoadingError: services_prices is not associated to services_user_prices!
const result= await db.services_user_prices.findOne({
where: { is_active: 1, user_id: 123 }, include:[{db.services_prices}]
});
in the db services_user_prices has foreign key to services_prices table
what am i doing wrong?
Well if you are using sequelize then you need to update your model because
by default, sequelize will be looking for foreign key starts with model name like
you have defined bundle_price_id as a foreign key for services_prices.
You need to change your column name to services_price_id then it will get fixed.
or if you want to use bundle_price_id you need to define it in your model relation as.
Model.belongsTo(models.ModelName, { foreignKey: 'your_key'} )
Please feel free if you need to ask anything else.
As complement of the above answer you need to add an identifier with as: on the association like this:
Model.belongsTo(models.ModelName, { foreignKey: 'your_key', as:'your_identifier' } )
Then when you do the include on the method you also call the identifier:
await db.services_user_prices.findOne({
where: { is_active: 1, user_id: 123 },
include:[{
model: db.services_prices
as: 'your_identifier'
}]
});
If you don't define the foreignKey field, the as field will set the column name.
i want to get user's images at limit 2 from Follow model.
Models
const Follow = connector.define('Follow', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
follower_id: {
type: Sequelize.INTEGER,
allowNull: true
},
target_id: {
type: Sequelize.INTEGER,
allowNull: true
},
isDelete: {
type: Sequelize.BOOLEAN,
allowNull: false
},
create_dt,
delete_dt
}
const User = connector.define('User', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
},
profile_img: {
type: Sequelize.STRING,
allowNull: true
},
bio: {
type: Sequelize.STRING,
allowNull: true
},
phone: {
type: Sequelize.STRING,
allowNull: true
},
gender: {
type: Sequelize.STRING,
allowNull: true
},
website: {
type: Sequelize.STRING,
allowNull: true
},
isDelete: {
type: Sequelize.BOOLEAN,
allowNull: false
},
create_dt,
update_dt,
delete_dt
}
const Image = connector.define('Image', {
no: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
file: {
type: Sequelize.STRING,
allowNull: false
},
location: {
type: Sequelize.STRING,
allowNull: true
},
caption: {
type: Sequelize.STRING,
allowNull: true
},
tags: {
type: Sequelize.STRING,
allowNull: true
},
isDelete: {
type: Sequelize.BOOLEAN,
allowNull: false
},
create_dt,
update_dt,
delete_dt,
user_id: {
type: Sequelize.INTEGER,
allowNull: true
}
}
and, join
User.hasMany(Image, {foreignKey: 'user_id'})
Image.belongsTo(User, {foreignKey: 'user_id'})
User.hasMany(Follow, {foreignKey: 'follower_id'})
Follow.belongsTo(User, {foreignKey: 'follower_id'})
User.hasMany(Follow, {foreignKey: 'target_id'})
Follow.belongsTo(User, {foreignKey: 'target_id'})
so, i tried get user's images from follow by use include.
const followerImages = await Follow.findAll({
attributes: ['target_id'],
where:{
follower_id: loginUser_id
},
include:[
{
model: User,
required: true,
attributes: ['username', 'email', 'profile_img'],
include:[
{
model: Image,
required: true
}
]
}
]
})
but i want to get images at limit 2.
so i tried that
const followerImages = await Follow.findAll({
attributes: ['target_id'],
where:{
follower_id: loginUser_id
},
include:[
{
model: User,
required: true,
attributes: ['username', 'email', 'profile_img'],
include:[
{
model: Image,
required: true,
limit: 2
}
]
}
]
})
but it makes bugs i cant understand.
images field is a array contain empty object at 4.
all same..
what is the problem?
how can i solve this problem??
You can try :
include:[
{
model: Image,
attributes : ['id','user_id','image'] , // <---- don't forget to add foreign key ( user_id )
separate : true, // <--- Run separate query
limit: 2
}
]
Limit causes the issues some time on nested level , so it always safe to run that query separately.