I have a problem, I need to return an array just from my flows relationship. How can I get an array with a list of the flows of all companies?
My model and migrations are correct, I just don't know how to make the query return only the flows.
Company Model
module.exports = (sequelize) => {
const company = sequelize.define('company', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
}
})
company.hasMany(sequelize.models.flow, {foreignKey: 'company_id', as: 'flows'})
}
Flow model
module.exports = (sequelize) => {
const flow = sequelize.define('flow', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
company_id: {
allowNull: false,
type: DataTypes.INTEGER
},
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
}
})
flow.belongsTo(sequelize.models.company, {foreignKey: 'company_id', as: 'company'})
}
Query
const companies = await ORM.models.company
.findAll({
include: [{
model: ORM.models.flow,
as: 'flows'
}]
})
This query is returning like this:
[
{
"id": 1,
"uuid": "f0c1a5e1-c54c-4083-8284-5a9b272e8ba1",
"name": "Company 1",
"created_at": "2021-02-11T05:47:55.830Z",
"updated_at": "2021-02-11T05:47:55.830Z",
"flows": [
{
"id": 1,
"company_id": 1,
"uuid": "768262d2-88b7-4e0f-81e8-30d7253aae65",
"name": "Flow 1",
"description": null,
"created_at": "2021-02-11T05:48:10.211Z",
"updated_at": "2021-02-11T05:48:10.211Z",
"companyId": 1
}
]
},
{
"id": 2,
"uuid": "3dea2541-a505-4f0c-a356-f1a2d449d050",
"name": "Company 1",
"created_at": "2021-02-11T05:48:11.872Z",
"updated_at": "2021-02-11T05:48:11.872Z",
"flows": [
{
"id": 2,
"company_id": 2,
"uuid": "3e66e8e6-3754-41e5-93ca-6e8ed49e2025",
"name": "Flow 2",
"description": null,
"created_at": "2021-02-11T05:48:20.743Z",
"updated_at": "2021-02-11T05:48:20.743Z",
"companyId": 2
}
]
}
]
I need to return like this:
[
{
"id":1,
"company_id":1,
"uuid":"768262d2-88b7-4e0f-81e8-30d7253aae65",
"name":"Flow 1",
"description":null,
"created_at":"2021-02-11T05:48:10.211Z",
"updated_at":"2021-02-11T05:48:10.211Z",
"companyId":1
},
{
"id":2,
"company_id":2,
"uuid":"3e66e8e6-3754-41e5-93ca-6e8ed49e2025",
"name":"Flow 2",
"description":null,
"created_at":"2021-02-11T05:48:20.743Z",
"updated_at":"2021-02-11T05:48:20.743Z",
"companyId":2
}
]
If you just want the flows related data, why to fetch company related data with flows in it? Perhaps, you could only fetch flows data.
const flows = await ORM.models.flow
.findAll({
where: ....,
..........
});
If anyhow, you still want to show the flows for particular companies without showing any attributes of the company model, just do something like this:
const companies = await ORM.models.company
.findAll({
attributes: [], //empty
include: [{
model: ORM.models.flow,
as: 'flows'
}]
});
Related
I am creating a chat application and trying to create a relationship between User and User through friendship. So far I can create a relationship, but in the end only one user assigned a friend. I'm using Express, sequalize with postgress deployed to heroku. I don't know how to achieve it, any help is appreciated
migration:
`enter code here`await queryInterface.createTable('users', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, } }, }); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, friend: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, status: { type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'), allowNull: false, defaultValue: 'PENDING', }, });
friendship model:
Friendship.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
user: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
friend: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
status: {
type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
allowNull: false,
defaultValue: 'PENDING',
},
},
{
sequelize,
underscored: true,
timestamps: false,
modelName: 'friendship',
}
);
associations:
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user',
otherKey: 'friend' });
Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' });
controller:
export const addFriend = async (req: Request, res: Response) => {
try {
const { friendId } = req.body;
const userId = req.decodedToken?.id;
const friend = await User.findByPk(friendId, {
attributes: { exclude: ['passwordHash'] },
include: [{ model: User, as: 'friends' }],
});
if (friend)
await Friendship.create({
user: userId,
friend: friend.id,
status: 'PENDING',
});
return res.status(200).json({ status: 'success' });
} catch (e) {
res.status(500).json({ error: 'The server cannot create the user' });
console.log(e);
}
};
response:
"users": {
"count": 2,
"rows": [
{
"id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"email": "admin",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": [
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friendship": {
"id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
"user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"status": "PENDING"
}
}
]
},
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": []
}
Edit:
I made something like this, it's not perfect, but it's good for me
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });
Please consider a many to many relationship.
An user can be a friend of many users.
Many users can be friends of one user.
You may found the how-to implement in the official doc: here.
Basically, use belongsToMany in both associations:
Implementation
The main way to do this in Sequelize is as follows:
const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
Movie.belongsToMany(Actor, { through: 'ActorMovies' });
Actor.belongsToMany(Movie, { through: 'ActorMovies' });
i got some problems while writing code, here is some information:
Models:
'use strict';
module.exports = (sequelize, DataTypes) => {
const news = sequelize.define('news', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
title: DataTypes.STRING,
slug: {
type: DataTypes.STRING(64),
unique: true
},
body: DataTypes.STRING,
postedBy: DataTypes.INTEGER
}, {});
news.associate = function(models) {
models.news.hasMany(models.news_ratings, {
as: 'rate',
foreignKey: models.news_ratings.newsId
})
};
return news;
};
///////////////
'use strict';
module.exports = (sequelize, DataTypes) => {
const news_rating = sequelize.define('news_ratings', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
user: DataTypes.INTEGER,
rating: DataTypes.INTEGER,
newsId: DataTypes.INTEGER
}, {});
news_rating.associate = function(models) {
models.news_ratings.belongsTo(models.news, {
foreignKey: models.news.id
})
};
return news_rating;
};
Controller:
router.get('/news/:from/:count', (req, res, next) => {
if (Number.isInteger(Number(req.params.from)) && Number.isInteger(Number(req.params.count))) {
models.news.findAll({
offset: Number(req.params.from),
limit: Number(req.params.count),
include: [{
as: 'rate',
model: models.news_ratings,
attributes: [
[sequelize.fn('AVG', sequelize.col('rating')), 'rate']
]
}]
})
.then(response => {
console.log(response)
res.json(response)
})
.catch(err => {
console.error(err)
res.status(500).end()
})
} else next()
})
This code returns this result (then fetching /news/0/1):
[{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "-0.3333"
}
]
}]
But I have 5 news in my database!
...And then I fetch /news/0/5, i got this:
[
{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "0.0000"
}
]
}
]
Look, rate is invalid! It should be -0.3333!
Can someone explain me, why this happen and how to resolve this issue?
Can someone help me I'm having problems inserting a record in the database with sequelize, created_at and updated_at are automatically filled and this is with this error:
"name": "SequelizeValidationError",
"errors": [
{
"message": "createdAt cannot be an array or an object",
"type": "string violation",
"path": "createdAt",
"value": "2020-05-28T22:04:45.023Z",
"origin": "CORE",
"instance": {
"id": null,
"placeId": "1",
"userId": 3,
"name": "Alex Santos",
"email": "customer#gmail.com",
"documento": "00000000000",
"phone": "(37)98596-9869",
"updatedAt": "2020-05-28T22:04:45.023Z",
"createdAt": "2020-05-28T22:04:45.023Z"
},
"validatorKey": "not_a_string",
"validatorName": null,
"validatorArgs": []
},
{
"message": "customer.updateAt cannot be null",
"type": "notNull Violation",
"path": "updateAt",
"value": null,
"origin": "CORE",
"instance": {
"id": null,
"placeId": "1",
"userId": 3,
"name": "Alex Santos",
"email": "customer#gmail.com",
"documento": "031.682.546-81",
"phone": "(37)98596-9869",
"updatedAt": "2020-05-28T22:04:45.023Z",
"createdAt": "2020-05-28T22:04:45.023Z"
},
"validatorKey": "is_null",
"validatorName": null,
"validatorArgs": []
}
]
}
Can someone provide any suggestions to help? I think in customer.js create() function is having some sort of miss from my side.
Could there be any other solution?
customer.js
/* jshint indent: 1 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('customer', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'id'
},
placeId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'places',
key: 'id'
},
field: 'place_id'
},
userId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'users',
key: 'id'
},
field: 'user_id'
},
customerId: {
type: DataTypes.INTEGER(11),
allowNull: true,
field: 'customer_id'
},
name: {
type: DataTypes.STRING(100),
allowNull: false,
field: 'name'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'email'
},
documento: {
type: DataTypes.STRING(16),
allowNull: false,
defaultValue: '',
field: 'documento'
},
phone: {
type: DataTypes.STRING(12),
allowNull: false,
field: 'phone'
},
createdAt: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'created_at'
},
updateAt: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'update_at'
}
}, {
tableName: 'customer'
});
};
CustomerController.js
const Customers = require('./../models/custumers')
const Sequelize = require('sequelize');
const db = require('../../bin/database');
const Customer = new Customers(db, Sequelize);
exports.create = async(req, res) => {
decodeToken = await jwt.decodeToken(req.headers['x-access-token'])
let userId = decodeToken.id
console.log(new Date())
let { placeId, customerId, name, email, documento, phone } = req.body
Customer.create({
placeId,
userId,
customerId,
name,
email,
documento,
phone
})
.then((Customer) => {
return res.status(200).send({ Customer: Customer })
}).catch(err => {
res.status(423).send(err);
});
}
The error message is telling you what is wrong. You defined the createdAt column as a String but it would appear that you are sending an object (very likely of type Date). The value of type Date is not a String, and so Sequelize is warning you with information like "validatorKey": "not_a_string" and "type": "string violation".
I don't know why you elected to store a timestamp as a String, but part of the fix is to change the column to type Date.
You also mentioned that the column value is filled automatically, but I don't see anywhere where that would take place. Unless you are explicitly setting a default value for the column and then not providing a value when committing the session, these columns will not be automatically filled.
The short answer is, change the column type to DATE and make sure to set a timestamp on the value before committing to the db.
Currently am having a problem with a simple query.
Sequelize query:
db[TABLE_NAMES.BOOKING].findAll({
order: [
[ db[TABLE_NAMES.USER_BOOKING_RELATION], db[TABLE_NAMES.BOOKING_STATUS], sequelize.literal('status = \'Attention\''), 'desc'],
['created_at', 'desc']
],
offset,
limit: max,
attributes: ['id', 'created_at'],
where: { school_id: schoolId },
include: [
{
attributes: ['id'],
model: db[TABLE_NAMES.USER_BOOKING_RELATION],
include: [
{
required: true,
attributes: ['status'],
model: db[TABLE_NAMES.BOOKING_STATUS],
where: { status: { [Sequelize.Op.in]: ['Attention', 'Pending', 'Invited'] } }
},
]
}
]
});
Models
const booking = sequelize.define(TABLE_NAMES.BOOKING, {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
unique: true
},
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
deleted_at: {
type: DataTypes.DATE
}
});
const user_booking_relation = sequelize.define(TABLE_NAMES.USER_BOOKING_RELATION, {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
unique: true
},
user_id: {
type: DataTypes.UUID,
allowNull: false
},
booking_id: {
type: DataTypes.UUID,
allowNull: false
},
booking_status_id: {
type: DataTypes.UUID,
allowNull: false,
},
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
deleted_at: {
type: DataTypes.DATE
},
});
const booking_status = sequelize.define(TABLE_NAMES.BOOKING_STATUS, {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
unique: true
},
status: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
created_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
updated_at: {
type: DataTypes.DATE,
defaultValue: sequelize.literal('NOW()')
},
deleted_at: {
type: DataTypes.DATE
}
});
booking.hasMany(user_booking_relation, { foreignKey: 'booking_id', sourceKey: 'id' });
user_booking_relation.belongsTo(booking, { foreignKey: 'booking_id', targetKey: 'id' });
booking_status.hasMany(user_booking_relation, { foreignKey: 'booking_status_id', sourceKey: 'id' });
user_booking_relation.belongsTo(booking_status, { foreignKey: 'booking_status_id', targetKey: 'id' });
Generated sql
SELECT `booking`.*,
`user_booking_relations`.`id` AS `user_booking_relations.id`,
`user_booking_relations->booking_status`.`id` AS `user_booking_relations.booking_status.id`,
`user_booking_relations->booking_status`.`status` AS `user_booking_relations.booking_status.status`
FROM (SELECT `booking`.`id`, `booking`.`created_at`
FROM `booking` AS `booking`
WHERE (`booking`.`deleted_at` IS NULL AND `booking`.`school_id` = 'a97b42e5-c864-4a4a-870b-737dd9700124')
AND (SELECT `user_booking_relations`.`booking_id`
FROM `user_booking_relation` AS `user_booking_relations`
INNER JOIN `booking_status` AS `booking_status`
ON `user_booking_relations`.`booking_status_id` = `booking_status`.`id` AND
(`booking_status`.`deleted_at` IS NULL AND
`booking_status`.`status` IN ('Invited', 'Pending', 'Attention'))
WHERE ((`user_booking_relations`.`deleted_at` IS NULL) AND
`user_booking_relations`.`booking_id` = `booking`.`id`)
LIMIT 1) IS NOT NULL
ORDER BY `booking`.`created_at` DESC
LIMIT 0, 10) AS `booking`
LEFT OUTER JOIN ( `user_booking_relation` AS `user_booking_relations` INNER JOIN `booking_status` AS `user_booking_relations->booking_status` ON
`user_booking_relations`.`booking_status_id` = `user_booking_relations->booking_status`.`id` AND
(`user_booking_relations->booking_status`.`deleted_at` IS NULL AND
`user_booking_relations->booking_status`.`status` IN ('Invited', 'Pending', 'Attention')) )
ON `booking`.`id` = `user_booking_relations`.`booking_id` AND
(`user_booking_relations`.`deleted_at` IS NULL)
ORDER BY `user_booking_relations->booking_status`.status = 'Attention' DESC, `booking`.`created_at` DESC;
Result
// first page
// first page
[
{
"id": "4c74c307-3f7c-40c6-ba26-6d0e9f510bcc",
"created_at": "2020-05-30T20:15:07.000Z",
"user_booking_relations": [
{
"id": "7cb183c7-77cf-4fc8-9c98-eb2b8abf8d39",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "1e8c9250-61b5-4610-b913-bd7aee866d5d",
"created_at": "2020-06-01T14:48:00.000Z",
"user_booking_relations": [
{
"id": "0a9ba1a0-0929-4979-ba15-12c4903fd8a5",
"booking_status": {
"status": "Invited"
}
},
]
},
{
"id": "a1624f59-ebaa-4bc7-95b8-d0e96c1ec917",
"created_at": "2020-06-01T08:45:12.000Z",
"user_booking_relations": [
{
"id": "fdbc677b-2035-44d2-8d9a-ab304e5624ee",
"booking_status": {
"status": "Pending"
}
}
]
}
]
// second page
[
{
"id": "d18abf5c-c986-4c2c-a08d-02e1488745d8",
"created_at": "2020-05-30T20:14:10.000Z",
"user_booking_relations": [
{
"id": "585c0674-13cf-45ac-91bc-087b345a7b31",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "692ccef9-12b4-4aed-955b-11ce65512469",
"created_at": "2020-05-30T20:12:45.000Z",
"user_booking_relations": [
{
"id": "5c3d214d-833a-482d-aeb5-272af750f3bb",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "1a5a56a9-4a6e-4548-a4d8-b388e6a9ac02",
"created_at": "2020-05-30T20:09:43.000Z",
"user_booking_relations": [
{
"id": "cea240f4-2529-44ae-a82d-f53d2dbbd0fc",
"booking_status": {
"status": "Attention"
}
}
]
}
]
Expected result
// first page
[
{
"id": "4c74c307-3f7c-40c6-ba26-6d0e9f510bcc",
"created_at": "2020-05-30T20:15:07.000Z",
"user_booking_relations": [
{
"id": "7cb183c7-77cf-4fc8-9c98-eb2b8abf8d39",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "d18abf5c-c986-4c2c-a08d-02e1488745d8",
"created_at": "2020-05-30T20:14:10.000Z",
"user_booking_relations": [
{
"id": "585c0674-13cf-45ac-91bc-087b345a7b31",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "692ccef9-12b4-4aed-955b-11ce65512469",
"created_at": "2020-05-30T20:12:45.000Z",
"user_booking_relations": [
{
"id": "5c3d214d-833a-482d-aeb5-272af750f3bb",
"booking_status": {
"status": "Attention"
}
}
]
}
]
// second page
[
{
"id": "1a5a56a9-4a6e-4548-a4d8-b388e6a9ac02",
"created_at": "2020-05-30T20:09:43.000Z",
"user_booking_relations": [
{
"id": "cea240f4-2529-44ae-a82d-f53d2dbbd0fc",
"booking_status": {
"status": "Attention"
}
}
]
},
{
"id": "1e8c9250-61b5-4610-b913-bd7aee866d5d",
"created_at": "2020-06-01T14:48:00.000Z",
"user_booking_relations": [
{
"id": "0a9ba1a0-0929-4979-ba15-12c4903fd8a5",
"booking_status": {
"status": "Invited"
}
},
]
},
{
"id": "a1624f59-ebaa-4bc7-95b8-d0e96c1ec917",
"created_at": "2020-06-01T08:45:12.000Z",
"user_booking_relations": [
{
"id": "fdbc677b-2035-44d2-8d9a-ab304e5624ee",
"booking_status": {
"status": "Pending"
}
}
]
}
]
As we can see from the generated SQL, bookings with any of those statuses are initially selected and then sorted. I need Attention bookings to go first. How can I get around this or fix it? Any thoughts will be much appreciated.
Thanks,
Alex.
I am new in nodejs. I am creating new app using nodejs. i want to join two table city and state using hasmany relations.
Here is my state model state.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('state', {
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'state'
});
};
Here is my city model city.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('city', {
state: {
type: DataTypes.INTEGER(11),
allowNull: true
},
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'city'
});
};
This is my citycontroller.js
let City = require('../models').city;
let State = require('../models').state;
let message = require('../../config/message');
let Boom = require('boom');
module.exports = {
listCity: async(request,h) =>{
let stateid = request.query.stateid;
try{
let searchQuery = {};
if(stateid) searchQuery.state = stateid;
let listCity = await City.findAll({ where:searchQuery});
if(listCity.length){
let response = {
"statusCode": 200,
"message":message.DATAFOUND,
"result": listCity
};
return h.response(response).code(200);
}else{
return h.response(response).code(204);
}
}catch(err){
return Boom.badRequest(err.message);
}
},
};
Output:
{
"statusCode": 200,
"message": "Data found",
"result": [
{
"state": 1,
"name": "Los Angeles",
"id": 1,
"createdAt": null,
"updatedAt": null
},
{
"state": 1,
"name": "San Francisco",
"id": 2,
"createdAt": null,
"updatedAt": null
},
{
"state": 5,
"name": "Southhampton",
"id": 3,
"createdAt": null,
"updatedAt": null
}
]
}
Now it listing city details only. but i need to join state details also under each city.
If you want to select the data from the state table than define a relation in the state model.
module.exports = function(sequelize, DataTypes) {
const state = sequelize.define('state', {
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'state'
});
state.associate = function(model){
models.state.hasMany(models.city){
foreignKey: 'state'
}
return state;
}
};
Or if you want to select data from the city table than define a similar hasOne relation in city table.