Greetings to all the problem-solving enthusiasts out there! I'm currently in the process of revamping a previous project using Next.js, and I've hit a roadblock that has me stumped.
My current challenge involves establishing an association between an order and its line items. Despite setting up the associations correctly in Postbird, I'm encountering an error when fetching the data:
Error Message:
EagerLoadingError [SequelizeEagerLoadingError]: lineItem is not associated to order!
Here are the associations defined in server/index.js:
const conn = require("./conn");
const { Artist, LineItem, Order, Track, User, Vinyl } = require("./models");
//ASSOCIATIONS
User.hasMany(Order);
Order.belongsTo(User);
Order.hasMany(LineItem);
LineItem.belongsTo(Order);
Vinyl.hasMany(LineItem);
LineItem.belongsTo(Vinyl);
Vinyl.hasMany(Track);
Track.belongsTo(Vinyl);
Artist.hasMany(Vinyl);
Vinyl.belongsTo(Artist);
module.exports = { conn, Artist, LineItem, Order, Track, User, Vinyl };
Lastly, let's take a look at the API route:
import { Order, LineItem, Vinyl, Artist } from "../../../../server/models";
import { requireToken } from "../../../../customMiddleware";
const handler = async (req, res) => {
if (req.method === "GET") {
try {
const userOrders = await Order.findAll({
where: { userId: req.query.id },
include: {
model: LineItem,
attributes: ["id", "qty"],
include: {
model: Vinyl,
attributes: ["id", "name", "stock", "price", "img"],
include: {
model: Artist,
attributes: ["id", "name"],
},
},
},
});
userOrders.sort((a, b) => a.id - b.id);
res.status(200).json({ success: true, userOrders });
} catch (error) {
console.log(error);
res.status(500).json({
success: false,
message: `An error has occurred. Unable to fetch user order id# ${req.query.id}.`,
error,
});
}
}
};
export default requireToken(handler);
I'd like to mention that this setup is working perfectly fine in the old project, so I'm quite puzzled by the issue at hand.
If anyone has any suggestions or insights, they would be greatly appreciated!
I've experimented with rearranging the associations in various ways, but unfortunately, it hasn't made a difference.