From 90cfe21f05dfc83ab5b0b21413e0be9fe8327f70 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Fri, 5 Apr 2024 02:41:28 +0000 Subject: [PATCH] fixed some relations & fixed list/:id route --- backend/db/relations.js | 2 ++ backend/routes/listRoutes.js | 24 +++++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/db/relations.js b/backend/db/relations.js index 7cf231e..afe9ef1 100644 --- a/backend/db/relations.js +++ b/backend/db/relations.js @@ -41,6 +41,7 @@ Entry.belongsToMany(List, { foreignKey: 'entry_id', otherKey: 'list_id', onDelete: 'CASCADE', + as: 'entries', }); List.belongsToMany(Entry, { @@ -48,6 +49,7 @@ List.belongsToMany(Entry, { foreignKey: 'list_id', otherKey: 'entry_id', onDelete: 'CASCADE', + as: 'entries', }); Entry.hasMany(ListEntry, { foreignKey: 'entry_id', as: 'listEntries' }); diff --git a/backend/routes/listRoutes.js b/backend/routes/listRoutes.js index 9550d5c..6d17f59 100644 --- a/backend/routes/listRoutes.js +++ b/backend/routes/listRoutes.js @@ -2,6 +2,8 @@ const express = require('express'); const List = require('../models/List'); const ListEntry = require('../models/ListEntry'); const Entry = require('../models/Entry'); +const EntryId = require('../models/EntryId'); +const EntryRating = require('../models/EntryRating'); const router = express.Router(); @@ -36,8 +38,28 @@ router.get('/', async (req, res) => { // * GET - LIST BY ID router.get('/:id', async (req, res) => { try { - const list = await List.findByPk(req.params.id); + const list = await List.findByPk(req.params.id, { + include: [{ + model: Entry, + as: 'entries', // Make sure this matches your alias in the association, if any + through: { + attributes: [], // Exclude attributes from the join model, if you don't need them + }, + }], + }); + if (list) { + // Optionally, sort the entries here if needed, using JavaScript's sort() + // This is a workaround for the direct ordering limitation via Sequelize in many-to-many relationships + for (let i = 0; i < list.entries.length; i++) { + list.entries[i] = await Entry.findByPk(list.entries[i].id, + { + include: [ + { model: EntryId, as: 'entryId' }, + { model: EntryRating, as: 'entryRating' } + ] + }) + } res.status(200).json(list); } else { res.status(404).json({ message: 'List not found' });