I am using sequelize with mysql,
I have 3 models
posts
Comments
users
posts model
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
content: DataTypes.TEXT,
userId: DataTypes.INTEGER
}, {});
Post.associate = function(models) {
// associations can be defined here
Post.hasMany(models.Comment, {
foreignKey: 'postId',
as: 'comments',
onDelete: 'CASCADE',
})
Post.belongsTo(models.User, {
foreignKey: 'userId',
as: 'author',
onDelete: 'CASCADE',
})
};
return Post;
};
comments model
const user = require("./user");
module.exports = (sequelize, DataTypes) => {
const Comment = sequelize.define(
"Comment",
{
postId: DataTypes.INTEGER,
comment: DataTypes.TEXT,
userId: DataTypes.INTEGER,
},
{}
);
Comment.associate = function (models) {
// associations can be defined here
Comment.belongsTo(
models.User,
{
foreignKey: "userId",
as: "author",
me: "name",
},
{ name: user.name }
);
Comment.belongsTo(models.Post, {
foreignKey: "postId",
as: "post",
});
};
return Comment;
};
users model
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
name: DataTypes.STRING,
email: DataTypes.STRING,
},
{}
);
User.associate = function (models) {
// associations can be defined here
User.hasMany(models.Post, {
foreignKey: "userId",
as: "posts",
onDelete: "CASCADE",
});
User.hasMany(models.Comment, {
foreignKey: "userId",
as: "comments",
onDelete: "CASCADE",
});
};
return User;
};
and following is my response i am getting when i execute the following query
const getAllPosts = async (req, res) => {
try {
const posts = await models.Post.findAll({
include: [
{
model: models.Comment,
as: "comments"
},
{
model: models.User,
as: "author"
}
]
});
return res.status(200).json({ posts });
} catch (error) {
return res.status(500).send(error.message);
}
};
RESPONSE
"posts": [
{
"id": 1,
"title": "1st post ever on this server",
"content": "This is the content of the first post published on this type or architecture",
"userId": 1,
"createdAt": "2021-01-31T10:00:45.000Z",
"updatedAt": "2021-01-31T10:00:45.000Z",
"comments": [
{
"id": 1,
"postId": 1,
"comment": "this is the comment on first post",
"userId": 1, // Also need a key val pair of username and his email ID just instead of UserID
"createdAt": null,
"updatedAt": null
},
{
"id": 2,
"postId": 1,
"comment": "comment second",
"userId": 1,
"createdAt": "2021-01-31T15:34:27.000Z",
"updatedAt": "2021-01-31T15:34:27.000Z"
}
],
"author": {
"id": 1,
"name": "test user",
"email": "testuser#gmail.com",
"createdAt": null,
"updatedAt": null
}
}
]
}
I need the user name of commented user name and email for which i have fields in the table
but i am just getting user ID
how can i go about it,
I am very much new in sequelize, I tried but i am getting get same hasMany and benlongsTo results.
From what I see you doing, you need to run a nested include when getting the comment.
Try this modified code.
const getAllPosts = async (req, res) => {
try {
const posts = await models.Post.findAll({
include: [
{
model: models.Comment,
as: "comments",
include: [
{
model: models.User,
as: "author"
}
]
},
{
model: models.User,
as: "author"
}
]
});
return res.status(200).json({ posts });
} catch (error) {
return res.status(500).send(error.message);
}
};
Related
I have two tables:
const attr = {
name: {
type: DataTypes.STRING,
},
};
const Tags = createModel('Tags', attr, {});
and:
const attr = {
tagId: {
type: DataTypes.INTEGER,
references: { model: 'Tags', key: 'id' },
}
}
const Client = createModel('Client', attr, {})
Client.belongsTo(Tag, { foreignKey: 'tagId', as: 'tags' });
and my query is this:
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
and this is my response:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": {
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
}
but I want my tags to be an array, so I guest I have to define a one to many association, but everything I tried so far failed.
What I want is tags to be an array, where I can add multiple tag objects:
{
"id": 1,
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-22T00:00:00.000Z",
"tags": [
{
"id": 1,
"name": "New tag",
"createdAt": "2020-01-20T00:00:00.000Z",
"updatedAt": "2020-01-20T00:00:00.000Z"
}
]
}
Method1
We need new model as Client_Tag
const attr = {
clientId: {
type: DataTypes.INTEGER,
},
tagId: {
type: DataTypes.INTEGER,
},
};
const Client_Tag = createModel('Client_Tag', attr, {});
Client.belongsToMany(Tag, {
foreignKey: 'clientId',
otherKey: 'tagId',
through: models.Client_Tag,
as: 'tags'
});
const clientCount = await Client.findAll({
include: [ { model: Tags, as: 'tags' } ],
attributes: { exclude: 'tagId' }
});
Method2
const attr = {
name: {
type: DataTypes.STRING,
},
clientId: { // need clientId in tag model, and remove 'tagId' from client model
type: DataTypes.INTEGER,
}
};
const Tags = createModel('Tags', attr, {});
Client.belongsToMany(Tag, { foreignKey: 'tagId', as: 'tags' });
I would like to display some information about members, but I don't know how to resolve array of field 'time'. This is array, because it shows their login time. What should I do?
I used GraphQLString, but I am aware of this bad solution.
So I'm getting an error:
"message": "String cannot represent value: [\"12:08\"]",
Here is schema.js
const axios = require("axios");
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLSchema
} = require("graphql");
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: GraphQLString
}
})
});
//Root Query
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
users: {
type: new GraphQLList(memberType),
description: "List of members",
resolve(parent, args) {
return axios
.get("http://25.98.140.121:5000/data")
.then(res => res.data);
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
});
And here is JSON
[
{
"time": [
"12:08"
],
"nick": "Cogi12",
"name_and_surname: "John Steps"
},
{
"time": [
"12:16"
],
"nick": "haris22",
"name_and_surname": "Kenny Jobs"
},
{
"time": [
"12:07",
"12:08",
"12:17",
"12:19",
"12:45",
"13:25"
],
"nick": "Wonski",
"name_and_surname": "Mathew Oxford"
}
]
you can use GraphQLList along with GraphQLString for time type like this,
const memberType = new GraphQLObjectType({
name: "Member",
fields: () => ({
nick: {
type: GraphQLString
},
name_and_surname: {
type: GraphQLString
},
time: {
type: new GraphQLList(GraphQLString)
}
})
});
Context : I am having this problem were I am doing a query using sequilize an it only return's me an array with one position even though I have more than one field that correspond to the query.
This are my two involved models
This is my group.js model
module.exports = (sequelize, DataTypes) => {
const Group = sequelize.define('Group', {
name: DataTypes.STRING,
limit: DataTypes.STRING,
user_id: DataTypes.INTEGER
});
Group.associate = models => {
Group.belongsTo(models.User, { foreignKey: 'user_id' });
};
Group.associate = models => {
Group.hasMany(models.Movement, { foreignKey: 'group_id' });
};
return Group;
}
This is my movement.js model
module.exports = (sequelize, DataTypes) => {
const Mov = sequelize.define('Movement', {
description: DataTypes.STRING,
value: DataTypes.INTEGER,
group_id: DataTypes.INTEGER
});
Mov.associate = models => {
Mov.hasOne(models.Group, { foreignKey: 'group_id' });
};
return Mov;
}
This is my query (where you will see that I am doing an INNER JOIN to SUM the fields of the Movement table)
router.get('/', verify, async (req, res) => {
try {
const group = await Group.findAll({
attributes: [
'id',
'name',
'limit',
[sequelize.fn('SUM', sequelize.col('Movements.value')), 'total_spent'],
],
include: [{
attributes: [], // this is empty because I want to hide the Movement object in this query (if I want to show the object just remove this)
model: Movement,
required: true
}],
where: {
user_id: req.userId
}
});
if (group.length === 0) return res.status(400).json({ error: "This user has no groups" })
res.status(200).json({ groups: group }) //TODO see why this is onyl return one row
} catch (error) {
console.log(error)
res.status(400).json({ Error: "Error while fetching the groups" });
}
});
Problem is that it only return's one position of the expected array :
{
"groups": [
{
"id": 9,
"name": "rgrgrg",
"limit": 3454354,
"total_spent": "2533"
}
]
}
It should return 2 positions
{
"groups": [
{
"id": 9,
"name": "rgrgrg",
"limit": 3454354,
"total_spent": "2533"
},
{
"id": 9,
"name": "rgrgrg",
"limit": 3454354,
"total_spent": "2533"
}
]
}
This is the query sequilize is giving me:
SELECT `Group`.`id`, `Group`.`name`, `Group`.`limit`, SUM(`Movements`.`value`) AS `total_spent` FROM `Groups` AS `Group` INNER JOIN `Movements` AS `Movements` ON `Group`.`id` = `Movements`.`group_id` WHERE `Group`.`user_id` = 1;
I guess you need to add an appropriate group by clause as follows -
const group = await Group.findAll({
attributes: [
'id',
'name',
'limit',
[sequelize.fn('SUM', sequelize.col('Movements.value')), 'total_spent'],
],
include: [{
attributes: [], // this is empty because I want to hide the Movement object in this query (if I want to show the object just remove this)
model: Movement,
required: true
}],
where: {
user_id: req.userId
},
group: '`Movements`.`group_id`'
});
Many-to-many "through" table with multiple rows of identical foreign key pairs only returns one result?
I just ran into this bug and added this options to the main query:
{
raw: true,
plain: false,
nest: true
}
Then you just merge the query.
It's a workaround, but might help someone.
I'm having problems to use the findAll() method with associations from Sequelize.
I have two models: Posts and Authors (an author has many posts and one post has one author), that I have created with Sequelize-cli and then through the migration command npx sequelize db migrate:all i have created them in mysql. To keep things organized, I have the associations between the models in another migration file (created with npx sequelize init:migrations, after all the models already existent), so my code looks like this:
AUTHOR MODEL
'use strict';
module.exports = (sequelize, DataTypes) => {
const Author = sequelize.define('Author', {
authorName: {
type: DataTypes.STRING,
validate: {
is: ["^[a-z]+$",'i'],
}
},
biography: {
type: DataTypes.TEXT,
validate: {
notEmpty: true,
}
}
}, {});
Author.associate = function(models) {
Author.hasMany(models.Post);
};
return Author;
};
POST MODEL
'use strict';
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: {
type: DataTypes.STRING,
validate: {
is: ["^[a-z]+$",'i'],
notEmpty: true,
},
},
content: {
type: DataTypes.TEXT,
validate: {
notEmpty: true,
},
},
likes: {
type: DataTypes.INTEGER,
defaultValue: 0,
validate: {
isInt: true,
},
},
}, {});
Post.associate = function(models) {
// associations can be defined here
};
return Post;
};
ASSOCIATIONS FILE (MIGRATION) (showing only parts that matter)
up: (queryInterface, Sequelize) => {
return queryInterface.sequelize.transaction(t => {
return Promise.all([
queryInterface.addColumn('Posts','AuthorId', {
type: Sequelize.INTEGER,
references: {
model: 'Authors',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}, { transaction: t }),
queryInterface.addColumn('Posts', 'ImagesId', {
type: Sequelize.INTEGER,
references: {
model: 'Images',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}, { transaction: t }),
queryInterface.addColumn('Posts', 'CategoryId', {
type: Sequelize.INTEGER,
references: {
model: 'Categories',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}, { transaction: t }),
]);
});
This is working fine apparently, since in Mysql-Workbench it shows me the following:
But, when I try to use the findAll() like this:
const { Post, Author } = require('../models/index');
function(response) {
Post.findAll({
attributes: ['id', 'title', 'content', 'likes'],
include: {
model: Author,
}
})
.then(result => response.json(result))
.catch(error => response.send(`Error getting data. Error: ${error}`));
It gives me the following error:
SequelizeEagerLoadingError: Author is not associated to Post!
So, I dont know anymore how to proceed. I've been trying many others approaches, but all of then unsuccessfully. I read already many other questions here in StackOverFlow about how to solve this sort of problem, but those were unsuccessfully too.
Thanks in advance.
You need to define the association for Post also as you are querying upon Post model
Post.associate = function(models) {
Post.belongsTo((models.Author);
};
You need to add an association from both ends, Post -> Author and Author -> Post , this way you will never stuck in this kind of error.
Summarizing this documentation we have the following:
If you have these models:
const User = sequelize.define('user', { name: DataTypes.STRING });
const Task = sequelize.define('task', { name: DataTypes.STRING });
And they are associated like this:
User.hasMany(Task);
Task.belongsTo(User);
You can fetch them with its associated elements in these ways:
const tasks = await Task.findAll({ include: User });
Output:
[{
"name": "A Task",
"id": 1,
"userId": 1,
"user": {
"name": "John Doe",
"id": 1
}
}]
And
const users = await User.findAll({ include: Task });
Output:
[{
"name": "John Doe",
"id": 1,
"tasks": [{
"name": "A Task",
"id": 1,
"userId": 1
}]
}]
After a join operation among three models I received a valid result but I would rename the attributes generated by the join operation of the findAll
Query:
const orchards = await db.Area.findAll({
include: [db.AreaCoordinate, db.Crop],
attributes: ['id', 'name']
});
AreaCoordinate Model:
module.exports = function (sequelize, DataTypes) {
var AreaCoordinate = sequelize.define('AreaCoordinate', {
latitude: {
type: DataTypes.STRING(45),
allowNull: true
},
longitude: {
type: DataTypes.STRING(45),
allowNull: true
}
}, {
classMethods: {
associate: function (models) {
AreaCoordinate.belongsTo(models.Area, {foreignKey: 'areaId'});
}
}
});
return AreaCoordinate;
};
Crop Model:
module.exports = function (sequelize, DataTypes) {
var Crop = sequelize.define('Crop', {
name: {
type: DataTypes.STRING(45),
allowNull: true
},
lang: {
type: DataTypes.STRING(45),
allowNull: true
}
}, {
classMethods: {
associate: function (models) {
Crop.hasMany(models.Area, {foreignKey:'cropId'})
}
}
});
return Crop;
};
Area Model:
module.exports = function (sequelize, DataTypes) {
var Area = sequelize.define('Area', {
name: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
// example on how to add relations
Area.belongsTo(models.Crop, {foreignKey: 'cropId'});
Area.belongsTo(models.Orchard, {as: 'orchard'});
Area.hasMany(models.AreaCoordinate, {foreignKey:'areaId'})
}
}
});
return Area;
};
I would receive from the query a JSON like this:
{
"status": 200,
"status_message": "OK",
"data": {
"orchard": [
{
"name": "pantano",
"coordinates": [
{
"id": 115,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
},
{
"id": 116,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
}
],
"cropId": 10
}
]
}
}
But what I receive is (look AreaCoordinates and Crop):
{
"status": 200,
"status_message": "OK",
"data": {
"orchard": [
{
"name": "pantano",
"AreaCoordinates": [
{
"id": 115,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
},
{
"id": 116,
"latitude": "1",
"longitude": "2",
"createdAt": "2017-08-29T12:03:11.000Z",
"updatedAt": "2017-08-29T12:03:11.000Z",
"areaId": 28
}
],
"Crop": 10
}
]
}
}
I tried to set some alias for AreaCoordinates and Crop but I couldn't find a solution. Thank you in advance for your support.
Write query like this:
const result = await Table.findAll({
attributes: ['id', ['foo', 'bar']] //id, foo AS bar
});
By default in Sequelize association, it will set the attribute name as the related model name. For your case, the related model named AreaCoordinates, so the attribute name in return will be AreaCoordinates. You should use as. Modify yours and Try this:
###findAll Query:
const orchards = await db.Area.findAll({
include: [
{
model: db.AreaCoordinate,
as: 'coordinates'
}, {
model: db.Crop,
as: 'cropId',
attributes: ['id']
}],
attributes: ['id', 'name']
});
###Area Model
module.exports = function (sequelize, DataTypes) {
var Area = sequelize.define('Area', {
name: DataTypes.STRING
}, {
classMethods: {
associate: function (models) {
// example on how to add relations
Area.belongsTo(models.Crop, {
foreignKey: 'cropId',
as: 'cropId'
});
Area.belongsTo(models.Orchard, {as: 'orchard'});
Area.hasMany(models.AreaCoordinate, {
foreignKey:'areaId',
as: 'coordinates'
})
}
}
});
return Area;
};