Search code examples
javascriptsequelize.jsquerying

querying for a record and its associations with sequelize


Given a table Show and a table Venue, with the below associations:

Show.belongsTo(Venue, { foreignKey: { name: 'id_venue', allowNull: false } });
Venue.hasMany(Show);

I'm trying to grab one venue and all of its associated shows.

const getSingleVenue = async (req, res) => {
    try {
        const { venueName } = req.params;
        const venue = await Venue.findOne({
            where: {
                name: venueName,
            },
            include: [
                { model: Show }
            ]
        })
        res.send(venue);
    }
    catch(err) {
        console.log(err);
        res.send(400);
    }
}

Right now, I'm stuck on the error Unknown column 'show.venueId' in 'field list'.

Not sure how to edit my associations to give sequelize what it's looking for.


Solution

  • The problem is this Venue.hasMany(Show); Y're not defined the foreign key.

    Replace some code :

    Show.belongsTo(Venue, { foreignKey: { name: 'id_venue', allowNull: false } }); Venue.hasMany(Show);

    By

    Show.belongsTo(Venue, { foreignKey: { name: 'id_venue', allowNull: false } });
    Venue.hasMany(Show, { foreignKey: { name: 'id_venue', as: shows } };