I'm trying to accomplish the task of joining all associated models, and then retrieving the count of all the models
I would want the data to be returned as
product {
main_dish: {},
side_dish: {},
drink: {},
purchase_product_count: x,
purchased_products: []
}
I have constructed this in sequelize to try to do this.
await Product.findAll({
include: [{
model: MainCourse,
required: false,
}, {
model: SideDish,
required: false,
}, {
model: Drink,
required: false,
}, {
model: ProductPurchase,
required: false,
where: {
createdAt: {[Op.between]: [two_days_before, current_date]}
},
}],
attributes: {
include: ['*',
[Sequelize.literal(
"(SELECT COUNT(*) from product_purchases as p where p.purchase_product_id = products.product_id)"), "product_purchase_count"],
]
},
offset: 1 * 5,
limit: 5
})
.then((results) => {
console.log(results)
res.status(200).json(results)
})
.catch((err) => {
console.log(err)
res.status(400).json(err)
})
Attempting to run this eager load gives this error
column reference "product_id" is ambiguous
This is the sql generated by sequelize
SELECT "products".*, "main_course"."main_course_id" AS "main_course.main_course_id", "main_course"."type" AS "main_course.type", "main_course"."createdAt" AS "main_course.createdAt", "main_course"."updatedAt" AS "main_course.updatedAt", "main_course"."deletedAt" AS "main_course.deletedAt", "main_course"."main_product_id" AS "main_course.main_product_id", "side_dish"."side_dish_id" AS "side_dish.side_dish_id", "side_dish"."type" AS "side_dish.type", "side_dish"."createdAt" AS "side_dish.createdAt", "side_dish"."updatedAt" AS "side_dish.updatedAt", "side_dish"."deletedAt" AS "side_dish.deletedAt", "side_dish"."side_product_id" AS "side_dish.side_product_id", "drink"."drink_id" AS "drink.drink_id", "drink"."type" AS "drink.type", "drink"."createdAt" AS "drink.createdAt", "drink"."updatedAt" AS "drink.updatedAt", "drink"."deletedAt" AS "drink.deletedAt", "drink"."drink_product_id" AS "drink.drink_product_id", "product_purchases"."product_purchase_id" AS "product_purchases.product_purchase_id", "product_purchases"."price" AS "product_purchases.price", "product_purchases"."quantity" AS "product_purchases.quantity", "product_purchases"."createdAt" AS "product_purchases.createdAt", "product_purchases"."updatedAt" AS "product_purchases.updatedAt", "product_purchases"."deletedAt" AS "product_purchases.deletedAt", "product_purchases"."purchase_product_id" AS "product_purchases.purchase_product_id", "product_purchases"."restaurant_order_id" AS "product_purchases.restaurant_order_id" FROM (SELECT "products"."product_id", "products"."title", "products"."price", "products"."createdAt", "products"."updatedAt", "products"."deletedAt", "products"."restaurant_id", "products".*, (SELECT COUNT(*) from product_purchases as p where p.purchase_product_id = products.product_id) AS "product_purchase_count" FROM "products" AS "products" WHERE ("products"."deletedAt" IS NULL) LIMIT 5 OFFSET 5) AS "products" LEFT OUTER JOIN "main_courses" AS "main_course" ON "products"."product_id" = "main_course"."main_product_id" AND ("main_course"."deletedAt" IS NULL) LEFT OUTER JOIN "side_dishes" AS "side_dish" ON "products"."product_id" = "side_dish"."side_product_id" AND ("side_dish"."deletedAt" IS NULL) LEFT OUTER JOIN "drinks" AS "drink" ON "products"."product_id" = "drink"."drink_product_id" AND ("drink"."deletedAt" IS NULL) LEFT OUTER JOIN "product_purchases" AS "product_purchases" ON "products"."product_id" = "product_purchases"."purchase_product_id" AND ("product_purchases"."deletedAt" IS NULL AND "product_purchases"."createdAt" BETWEEN '2022-05-06 08:35:12.577 +00:00' AND '2022-05-08 08:35:12.577 +00:00');
According to pgadmin the problem starts when doing the join on main_courses
ERROR: column reference "product_id" is ambiguous
LINE 1: ...EFT OUTER JOIN "main_courses" AS "main_course" ON "products"...
I seem to not understand how the sequelize join works as I am using the ORM method of not having any columns be the same. The foreign keys are all different from 'product_id'. Is product_id getting created and joined again on the aggregation possibly? Why am I getting this error, and how can I achieve the result of getting the count of the product_purchases along with the joined array of purchased products.
Obviously I could just get the purchased_products.length and then add it to the object itself, but I'm trying to figure out if you can do it through sequelize without having to hack it in.
Related
I have 3 tables named:
//restaurants
columns ( id, name, restaurant_type_id(FK)
//restaurant_branches
columns ( id, name, restaurant_id(FK)
//restaurant_types
columns ( id, restaurant_type_name('italian', 'french'...etc))
I would like to filter restaurant_branches by restaurant_type_id using query params in my restaurant_branches.findAll(); action in the controller as the following.
const findAll = async (req, res) => {
let RestaurantTypeId= req.query.restaurantType ? parseInt(req.query.restaurantType): null ;
var type = RestaurantTypeId ? {where:{ restaurantTypeId: RestaurantTypeId }} : null ;
console.log(RestaurantTypeId);
await RestaurantBranch.findAll({
order: [
['id', 'ASC']
],
include:
[
{
model: Restaurant,
type,
include: [{
model: RestaurantType,
}
]
}
]
}).then((restaurantBranches) => {
return res.status(200).send({
message: "restaurant branches returned",
data: restaurantBranches
})
})
.catch((error) => {res.status(500).send(error.message);});
}
module.exports = {
findAll
}
//Sequelize Associations
db.RestaurantType.hasMany(db.Restaurant);
db.Restaurant.belongsTo(db.RestaurantType);
// Restaurant / Restaurant Branches
db.RestaurantBranch.belongsTo(db.Restaurant);
db.Restaurant.hasMany(db.RestaurantBranch);
Sequelize log:
Executing (default): SELECT "restaurant_branches"."id", "restaurant_branches"."name", "restaurant_branches"."description", "restaurant_branches"."email", "restaurant_branches"."phoneNumber", "restaurant_branches"."address", "restaurant_branches"."country_code", "restaurant_branches"."image", "restaurant_branches"."latitude", "restaurant_branches"."longitude", "restaurant_branches"."workingHours", "restaurant_branches"."workingDays", "restaurant_branches"."offDays", "restaurant_branches"."locationAddress", "restaurant_branches"."locationCity", "restaurant_branches"."status", "restaurant_branches"."hasParking", "restaurant_branches"."instruction", "restaurant_branches"."isActive", "restaurant_branches"."isDeleted", "restaurant_branches"."createdAt", "restaurant_branches"."updatedAt", "restaurant_branches"."restaurantId", "restaurant_branches"."cityId", "restaurant_branches"."districtId", "city"."id" AS "city.id", "city"."name" AS "city.name", "city"."code" AS "city.code", "city"."status" AS "city.status", "city"."isDeleted" AS "city.isDeleted", "city"."createdAt" AS "city.createdAt", "city"."updatedAt" AS "city.updatedAt", "city"."countryId" AS "city.countryId", "district"."id" AS "district.id", "district"."name" AS "district.name", "district"."isDeleted" AS "district.isDeleted", "district"."createdAt" AS "district.createdAt", "district"."updatedAt" AS "district.updatedAt", "district"."cityId" AS "district.cityId", "restaurant"."id" AS "restaurant.id", "restaurant"."name" AS "restaurant.name", "restaurant"."aboutUs" AS "restaurant.aboutUs", "restaurant"."phoneNumber" AS "restaurant.phoneNumber", "restaurant"."address" AS "restaurant.address", "restaurant"."latitude" AS "restaurant.latitude", "restaurant"."longitude" AS "restaurant.longitude", "restaurant"."image" AS "restaurant.image", "restaurant"."countryCode" AS "restaurant.countryCode", "restaurant"."restaurantRegisterDocument" AS "restaurant.restaurantRegisterDocument", "restaurant"."isDeleted" AS "restaurant.isDeleted", "restaurant"."createdAt" AS "restaurant.createdAt", "restaurant"."updatedAt" AS "restaurant.updatedAt", "restaurant"."restaurantTypeId" AS "restaurant.restaurantTypeId", "restaurant"."categoryId" AS "restaurant.categoryId", "restaurant"."userId" AS "restaurant.userId", "restaurant->restaurant_type"."id" AS "restaurant.restaurant_type.id", "restaurant->restaurant_type"."name" AS "restaurant.restaurant_type.name", "restaurant->restaurant_type"."photo" AS "restaurant.restaurant_type.photo", "restaurant->restaurant_type"."createdAt" AS "restaurant.restaurant_type.createdAt", "restaurant->restaurant_type"."updatedAt" AS "restaurant.restaurant_type.updatedAt" FROM "restaurant_branches" AS "restaurant_branches" LEFT OUTER JOIN "cities" AS "city" ON "restaurant_branches"."cityId" = "city"."id" LEFT OUTER JOIN "districts" AS "district" ON "restaurant_branches"."districtId" = "district"."id" LEFT OUTER JOIN "restaurants" AS "restaurant" ON "restaurant_branches"."restaurantId" = "restaurant"."id" LEFT OUTER JOIN "restaurant_types" AS "restaurant->restaurant_type" ON "restaurant"."restaurantTypeId" = "restaurant->restaurant_type"."id" ORDER BY "restaurant_branches"."id" ASC;
so far I'm doing this, and I get All the restaurant branches if I GET request to this URL:
{{URL}}/restaurant_branches?restaurantType=2
what I'd like to be getting instead is all the restaurant branches whom their restaurants belong to the restaurant type with id 2
Any help or guidance is highly appreciated.
You included where condition in include option as a type prop that's why it does not work as expected. You just need to indicate where either with your condition or as an empty object:
var where = RestaurantTypeId ? { restaurantTypeId: RestaurantTypeId } : {} ;
include:
[
{
model: Restaurant,
where,
include: [{
model: RestaurantType,
}
]
}
]
I have a Convos table, which has many Messages.
What I want: pull all convos and last message. Order the convos by last_message.created_at
models.Convos.findAll({
include: [
{
model: models.Messages,
as: "last_message",
order: [ [ 'created_at', 'DESC' ]],
limit: 1,
}
],
where:{
[Op.or]: [
{
sender_id: req.decoded.id
},
{
recipient_id: req.decoded.id
}
],
},
)}
The closest I've gotten to ordering is with :
order: [
[{model: models.Messages, as: 'last_message'}, 'created_at', 'DESC'],
],
But this gives the error:
`Unhandled rejection SequelizeDatabaseError: missing FROM-clause entry for table "last_message"`
From here, I am guessing this error may allude that there are convos without any messages, making last_message.created_at undefined (I could be completely misunderstanding this error though).
So, from there, I have been trying to add a clause to the where statement that only pulls convos that have at least 1 message. Here are a bunch of things I've tried, and they all throw an error:
adding to where:
Sequelize.literal("`last_message`.`id` IS NOT NULL")
'$models.Messages.id$': { [Op.ne]: null },
Sequelize.fn("COUNT", Sequelize.col("last_message")): { [Op.gt]: 0 }
'$last_message.id$': { [Op.ne]: null }
'$last_message.id$': {
[Op.ne]: null
}
I've also tried having instead of a where statement:
having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col('$last_message.id$')), '>=', 0)
How can I properly sort the convos by it's associated record, last_message.created_at?
UPDATE - RELEVANT PARTS OF CONVOS MODEL
"use strict";
module.exports = (sequelize, DataTypes) => {
let Convos = sequelize.define(
"Convos",
{
sender_id: {
type: DataTypes.INTEGER,
references: {
model: "Users",
key: "id"
}
},
recipient_id: {
type: DataTypes.INTEGER,
references: {
model: "Users",
key: "id"
}
},
created_at: DataTypes.DATE,
updated_at: DataTypes.DATE
},
{
timestamps: false,
freezeTableName: true,
schema: "public",
tableName: "convos"
}
);
Convos.associate = models => {
Convos.hasMany(models.Messages, {
as: "last_message",
foreignKey: "convo_id",
sourceKey: "id"
});
};
return Convos;
};
UPDATE
I've figured out the issue is using Sequelize.literal when the associated model has limit. For example, this works:
models.Convos.findAll({
include: [
{
model: models.Messages,
as: "last_message",
order: [ [ 'created_at', 'DESC' ]],
//limit: 1,
required: true,
duplicating: false,
},
],
where: {
[Op.or]: [
{
sender_id: req.decoded.id
},
{
recipient_id: req.decoded.id
}
],
},
order: [[Sequelize.literal(`last_message.created_at`), 'DESC']],
offset: offset,
limit: 10,
}).then(convos => { ....
But when I uncomment the limit: 1 in the include part, I get the error:
Unhandled rejection SequelizeDatabaseError: missing FROM-clause entry for table "last_message"
Here is the query logs without limit 1:
Executing (default): SELECT "Convos"."id", "Convos"."sender_id", "Convos"."recipient_id", "Convos"."created_at", "Convos"."updated_at", "last_message"."id" AS "last_message.id", "last_message"."body" AS "last_message.body", "last_message"."read" AS "last_message.read", "last_message"."group_meeting_id" AS "last_message.group_meeting_id", "last_message"."user_id" AS "last_message.user_id", "last_message"."created_at" AS "last_message.created_at", "last_message"."updated_at" AS "last_message.updated_at", "last_message"."convo_id" AS "last_message.convo_id", "last_message->user"."id" AS "last_message.user.id", "last_message->user"."first_name" AS "last_message.user.first_name", "last_message->user"."avatar_file_name" AS "last_message.user.avatar_file_name", "senderUser"."id" AS "senderUser.id", "senderUser"."first_name" AS "senderUser.first_name", "senderUser"."avatar_file_name" AS "senderUser.avatar_file_name", "recipientUser"."id" AS "recipientUser.id", "recipientUser"."first_name" AS "recipientUser.first_name", "recipientUser"."avatar_file_name" AS "recipientUser.avatar_file_name" FROM "public"."convos" AS "Convos" INNER JOIN "public"."msgs" AS "last_message" ON "Convos"."id" = "last_message"."convo_id" LEFT OUTER JOIN "public"."users" AS "last_message->user" ON "last_message"."user_id" = "last_message->user"."id" LEFT OUTER JOIN "public"."users" AS "senderUser" ON "Convos"."sender_id" = "senderUser"."id" LEFT OUTER JOIN "public"."users" AS "recipientUser" ON "Convos"."recipient_id" = "recipientUser"."id" WHERE ("Convos"."sender_id" = 32 OR "Convos"."recipient_id" = 32) ORDER BY last_message.created_at DESC LIMIT 10 OFFSET 70;
Query with limit: 1:
Executing (default): SELECT "Convos"."id", "Convos"."sender_id", "Convos"."recipient_id", "Convos"."created_at", "Convos"."updated_at", "senderUser"."id" AS "senderUser.id", "senderUser"."first_name" AS "senderUser.first_name", "senderUser"."avatar_file_name" AS "senderUser.avatar_file_name", "recipientUser"."id" AS "recipientUser.id", "recipientUser"."first_name" AS "recipientUser.first_name", "recipientUser"."avatar_file_name" AS "recipientUser.avatar_file_name" FROM "public"."convos" AS "Convos" LEFT OUTER JOIN "public"."users" AS "senderUser" ON "Convos"."sender_id" = "senderUser"."id" LEFT OUTER JOIN "public"."users" AS "recipientUser" ON "Convos"."recipient_id" = "recipientUser"."id" WHERE ("Convos"."sender_id" = 32 OR "Convos"."recipient_id" = 32) ORDER BY last_message.created_at DESC LIMIT 10 OFFSET 0;
Here are some links that were useful in understanding limit is causing the issue, but I have still not found a solution that solves this problem.
Link 1
Link 2
Link 3
Link 4
Thanks!
Disclaimer: I do not know sequelize. And - there are three documented versions and you have not stated which one you are using.
What I want: pull all convos and last message. Order the convos by
last_message.created_at
I can offer a SQL (Postgres) solution.
I assume a convos table (something like):
CREATE TABLE convos (
id INT PRIMARY KEY,
sender_id INT,
recipient_id INT
);
and a messages table
CREATE TABLE messages (
id INT PRIMARY KEY,
convo_id INT REFERENCES convos (id),
created_at timestamp without time zone
);
And some test data:
INSERT INTO
convos (id, sender_id, recipient_id)
VALUES (1,1,1), (2,2,2), (3,3,4);
INSERT INTO
messages (id, convo_id, created_at)
VALUES
(1,1, '1990-07-24'),
(2,1, '2019-07-24'),
(3,2, '1990-07-24'),
(4,2, '2019-07-24'),
(5,3, null);
When you want to query the convos table and fetch the latest message from messages table you will have to use the result from messages in a subquery (or a CTE, or lateral join, ...).
For example:
SELECT
convos.sender_id,
convos.recipient_id,
messages.last_message_date
FROM convos
LEFT JOIN
(
SELECT convo_id, max(created_at) as last_message_date
FROM messages
GROUP BY convo_id
) messages ON convos.id=messages.convo_id
ORDER BY messages.last_message_date DESC
So for sequelize.js - you have to find out how it does subqueries with associated models and use the result.
I have one filter query in sequelize with dynamic where clause as below,
let ticketnotificationsWhere = {};
if (req.query.department) {
ticketnotificationsWhere.department = req.query.department;
}
if (req.query.ticketid) {
ticketnotificationsWhere.ticketid = req.query.ticketid;
}
let ticketWhere = {};
if (req.query.isactionable) {
ticketWhere.isactionable = req.query.isactionable;
}
if (req.query.maintypeid) {
ticketWhere.maintypeid = req.query.maintypeid;
}
if (req.query.typeid) {
ticketWhere.typeid = req.query.typeid;
}
if (req.query.subtypeid) {
ticketWhere.subtypeid = req.query.subtypeid;
}
let ticketdetailsWhere = {};
if (req.query.customerid) {
ticketdetailsWhere.customerid = req.query.customerid;
}
return ticketdb.ticketnotifications.findAndCountAll({
limit: req.query.pageSize,
offset: req.query.page,
where:ticketnotificationsWhere,
attributes: ['id', 'ticketid', 'createdby', 'createddate', 'status'],
include:[{
model:ticketdb.tickets,
required: true,
where:ticketWhere,
attributes: ['isactionable'],
include:[{
model:ticketdb.ticketdetails,
required: true,
where:ticketdetailsWhere,
attributes: ['poid', 'productid', 'shippingreferenceno', 'customerid', 'issueqty']
},
{
model:ticketdb.maintypemaster,
attributes: [['name', 'maintypename']]
},
{
model:ticketdb.typemaster,
attributes: [['name', 'typename']]
},
{
model:ticketdb.subtypemaster,
attributes: [['name', 'subtypename']],
},
{
model:ticketdb.ticketsource,
attributes: ['sourcename']
}]
}]
})
The problem is that only where clause of ticketnotifications goes in actual SQL where clause, rest where conditions tickets and ticketdetails goes into JOIN which is wrong. Even Limit clause is not generating. The generated sql is as below,
SELECT count("ticketnotifications"."id") AS "count" FROM
"ticketnotifications" AS "ticketnotifications" INNER JOIN "tickets" AS
"ticket" ON "ticketnotifications"."ticketid" = "ticket"."ticketid" AND
"ticket"."isactionable" = true AND "ticket"."maintypeid" = 18 AND
"ticket"."typeid" = 70 AND "ticket"."subtypeid" = 240 INNER JOIN
"ticketdetails" AS "ticket.ticketdetail" ON "ticket"."ticketid" =
"ticket.ticketdetail"."ticketid" LEFT OUTER JOIN "maintypemaster" AS
"ticket.maintypemaster" ON "ticket"."maintypeid" =
"ticket.maintypemaster"."maintypeid" LEFT OUTER JOIN "typemaster" AS
"ticket.typemaster" ON "ticket"."typeid" =
"ticket.typemaster"."typeid" LEFT OUTER JOIN "subtypemaster" AS
"ticket.subtypemaster" ON "ticket"."subtypeid" =
"ticket.subtypemaster"."subtypeid" LEFT OUTER JOIN "ticketsource" AS
"ticket.ticketsource" ON "ticket"."sourceid" =
"ticket.ticketsource"."sourceid" WHERE "ticketnotifications"."ticketid" = 123;
What I expect is
SELECT count("ticketnotifications"."id") AS "count" FROM
"ticketnotifications" AS "ticketnotifications" INNER JOIN "tickets" AS
"ticket" ON "ticketnotifications"."ticketid" = "ticket"."ticketid" INNER JOIN
"ticketdetails" AS "ticket.ticketdetail" ON "ticket"."ticketid" =
"ticket.ticketdetail"."ticketid" LEFT OUTER JOIN "maintypemaster" AS
"ticket.maintypemaster" ON "ticket"."maintypeid" =
"ticket.maintypemaster"."maintypeid" LEFT OUTER JOIN "typemaster" AS
"ticket.typemaster" ON "ticket"."typeid" =
"ticket.typemaster"."typeid" LEFT OUTER JOIN "subtypemaster" AS
"ticket.subtypemaster" ON "ticket"."subtypeid" =
"ticket.subtypemaster"."subtypeid" LEFT OUTER JOIN "ticketsource" AS
"ticket.ticketsource" ON "ticket"."sourceid" =
"ticket.ticketsource"."sourceid" WHERE "ticketnotifications"."ticketid" = 123 AND
"ticket"."isactionable" = true AND "ticket"."maintypeid" = 18 AND
"ticket"."typeid" = 70 AND "ticket"."subtypeid" = 240
LIMIT 10 OFFSET 0;
I searched a lot and got solution like setting where condition in $$ but this is for one column, I want to add/set where clause dynamically as per filters.
Any idea what I'm doing wrong?
You can you Operaters in sequelize: Operaters
so, you code can be like this:
return ticketdb.ticketnotifications.findAndCountAll({
limit: req.query.pageSize,
offset: req.query.page,
where: { [Op.and]: [{ticketId: req.query.ticketid}, {isactionable: req.query.isactionable}, {maintypeid: 18}]},
include:[{
model:ticketdb.tickets,
required: true,
where:ticketWhere,
attributes: ['isactionable'],
include:[{
model:ticketdb.ticketdetails,
required: true,
where:ticketdetailsWhere,
},
{
model:ticketdb.maintypemaster,
attributes: [['name', 'maintypename']]
},
{
model:ticketdb.typemaster,
attributes: [['name', 'typename']]
},
{
model:ticketdb.subtypemaster,
attributes: [['name', 'subtypename']],
},
{
model:ticketdb.ticketsource,
attributes: ['sourcename']
}]
}]
Hope it can help you.
Let modify it as you want to.
I have the following models:
const User = Sequelize.define('user', {
login: Sequelize.DataTypes.STRING,
password: Sequelize.DataTypes.STRING,
is_manager: Sequelize.DataTypes.BOOLEAN,
notes: Sequelize.DataTypes.STRING
});
const Bike = Sequelize.define('bike', {
model: Sequelize.DataTypes.STRING,
photo: Sequelize.DataTypes.BLOB,
color: Sequelize.DataTypes.STRING,
weight: Sequelize.DataTypes.FLOAT,
location: Sequelize.DataTypes.STRING,
is_available: Sequelize.DataTypes.BOOLEAN
});
const Rate = Sequelize.define('rate', {
rate: Sequelize.DataTypes.INTEGER
});
Rate.belongsTo(User);
User.hasMany(Rate);
Rate.belongsTo(Bike);
Bike.hasMany(Rate);
And I'd like to select bikes with their average rates, plus rates of the current user for each bike:
Bike.findAll({
attributes: {include: [[Sequelize.fn('AVG', Sequelize.col('rates.rate')), 'rate_avg']],
},
include: [{
model: Rate,
attributes: []
}, {
model: Rate,
attributes: ['rate'],
include: [{
model: User,
attributes: [],
where: {
login: req.user.login
}
}]
}],
group: Object.keys(Bike.rawAttributes).map(key => 'bike.' + key) // group by all fields of Bike model
})
It constructs the following query: SELECT [bike].[id], [bike].[model], [bike].[photo], [bike].[color], [bike].[weight], [bike].[location], [bike].[is_available], AVG([rates].[rate]) AS [rate_avg], [rates].[id] AS [rates.id], [rates].[rate] AS [rates.rate] FROM [bikes] AS [bike] LEFT OUTER JOIN [rates] AS [rates] ON [bike].[id] = [rates].[bikeId] LEFT OUTER JOIN ( [rates] AS [rates] INNER JOIN [users] AS [rates->user] ON [rates].[userId] = [rates->user].[id] AND [rates->user].[login] = N'user' ) ON [bike].[id] = [rates].[bikeId] GROUP BY [bike].[id], [bike].[model], [bike].[photo], [bike].[color], [bike].[weight], [bike].[location], [bike].[is_available];
And fails: SequelizeDatabaseError: The correlation name 'rates' is specified multiple times in a FROM clause.
How do I write the query right? I need Sequelize to assign another alias to the rates table used in the 2nd join (and add its columns to the GROUP BY clause, but that's the next step).
You can do multiple inner joins with same table by adding extra same association with that model but with a different alias that is as: 'alias1' , as: 'alias2' ,... - all this existing with the same model + same type of association.
Also posted this solution at github issue: https://github.com/sequelize/sequelize/issues/7754#issuecomment-783404779
E.g. for Chats that have many Receiver
Associations (Duplicating for as many needed)
Chat.hasMany(Receiver, {
// foreignKey: ...
as: 'chatReceiver',
});
Chat.hasMany(Receiver, {
// foreignKey: ...
as: 'chatReceiver2',
});
Now you are left to include associated model multiple times all with different alias so it does not gets overridden.
So you can use them in query as below:
Chat.findAll({
attributes: ["id"],
include: [{
required: true,
model: Receiver,
as: 'chatReceiver', // Alias 1
attributes: [],
where: { userID: 1 }, // condition 1
}, {
required: true,
model: Receiver,
as: 'chatReceiver2', // Alias 2
attributes: [],
where: { userID: 2 }, // condition 2 as needed
}]
});
Solution :
Bike.findAll({
attributes: {include: [[Sequelize.fn('AVG', Sequelize.col('rates.rate')), 'rate_avg']],
},
include: [{
model: Rate,
attributes: []
}, {
model: Rate,
required : false , // 1. just to make sure not making inner join
separate : true , // 2. will run query separately , so your issue will be solved of multiple times
attributes: ['rate'],
include: [{
model: User,
attributes: [],
where: {
login: req.user.login
}
}]
group : [] // 3. <------- This needs to be managed , so please check errors and add fields as per error
}],
group: Object.keys(Bike.rawAttributes).map(key => 'bike.' + key) // group by all fields of Bike model
})
NOTE : READ THE COMMENTS
Sequelize doesn't support including through the same association twice (see here, here, and here). At the model level, you can define 2 different associations between Bike and Rate, but having to change the model, adding new foreign keys etc, is a very hacky solution.
Incidentally, it wouldn't solve your other problem, which is that you're grouping only by Bike but then want to select the user's rate. To fix that, you'd also have to change your grouping to include the user rates. (Note that if a user has more than 1 rate per bike, that might also create some inefficiency, as the rates for the bike are averaged repeatedly for each of the user's rates.)
A proper solution would be using window functions, first averaging the rates per bike and then filtering out all the rates not belonging to the logged in user. Might look something like this:
SELECT *
FROM (
SELECT bike.*,
users.login AS user_login,
AVG (rates.rate) OVER (PARTITION BY bike.id) AS rate_avg
FROM bike
INNER JOIN rates ON rates.bikeId = bike.id
INNER JOIN users ON rates.userId = users.id
)
WHERE user_login = :req_user_login
Unfortunately, as far as I'm aware sequelize doesn't currently support subqueries in the FROM clause and using window functions in this way, so you'd have to fall back to a raw query.
prompt how to use JOIN in Sequelize ?
I have the following code:
db.User.findAll({
attributes: ['id'],
where: {vipEnd: {lt: expiresVip}, vip: true},
limit: 100,
order: 'id'
}).then(function(users) {
In terms of 4, it looks like this:
SELECT "vkId" AS "id"
FROM "user" AS "user"
WHERE "user"."vipEnd" < 1469699683 --expiresVip
AND "user"."vip" = true
ORDER BY id
LIMIT '100';
How to achieve such a result?
SELECT "vkId" AS "id"
FROM "user" AS "user"
LEFT JOIN "notification" ON "notification"."userId" = "user"."vkId"
WHERE "user"."vipEnd" < 1469699683
AND "user"."vip" = true
AND "notification"."type" = 4
AND "notification"."expiresVipDate" < 1469699683
ORDER BY id
LIMIT '100';
Thank you!
You need to define association for models.
ex:
db.User.hasMany(db.Notification, {foreignKey: 'UserId'});
use properties include in sequelize:
db.User.findAll({
include: [{
model: db.Notification,
required: true//true INNER JOIN, false LEFT OUTER JOIN - default LEFT OUTER JOIN
}]}).then(function(user) {}, function(err) {
res.json(err, 400);});
You should consult more here
http://docs.sequelizejs.com/en/latest/docs/associations/