fixed some relations & fixed list/:id route
This commit is contained in:
1 parent
2f27c4cfdf
commit
90cfe21f05
2 files changed
+25
-1
No files matched your search
@@ -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' });
|
||||
|
||||
@@ -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' });
|
||||
|
||||
Reference in new issue
Block a user