最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Issues with many to many relation with sequelize in my controller - Stack Overflow

programmeradmin2浏览0评论

This is my first time here, and I hope I can provide you with all the information you need.

I am using Sequelize for a project I am working on after completing my web development training. I have many many-to-many relationships between my tables. I’ve read the Sequelize version 6 documentation to correctly set up the associations with the appropriate models.

So, I have multiple files. One initializes my Sequelize connection (database.js):

import { Sequelize } from "sequelize";
import * as dotenv from 'dotenv';

dotenv.config();

const sequelize = new Sequelize(process.env.PG_URL, {
    define: {
        underscored: true,
    },
    logging: console.log,
})

export default sequelize; 

Then, I have two files for my model and associations. Here’s an example of the match_profile model:

import { Model, DataTypes } from 'sequelize';
import sequelize from "../config/database.js";

class Match_Profile extends Model { };

Match_Profile.init({
    like: {
        type: DataTypes.ENUM('pending', 'like')
    }
},
    {
        sequelize,
        modelName: 'Match_Profile',
        tableName: 'match_profile',
        id: false,
    });

Match_Profile.removeAttribute('id');


export default Match_Profile;

Finally, I define all my associations in a file called association.js, which I execute in another file, init-db.js. Here’s an example of an association:

    Profile.belongsToMany(Match, { through: Match_Profile, foreignKey: 'profile_id', constraints: false });
    Match.belongsToMany(Profile, { through: Match_Profile, foreignKey: 'match_id', constraints: false });

    Match.hasMany(Match_Profile, { foreignKey: 'match_id' });
    Match_Profile.belongsTo(Match, { foreignKey: 'match_id' });
    Profile.hasMany(Match_Profile, { foreignKey: 'profile_id' });
    Match_Profile.belongsTo(Profile, { foreignKey: 'profile_id' });

However, when I try to add an entry to my join table in the controller, it doesn't work:

 try {

            const test1 = { match_id: 1, profile_id: 1, like: "like" };
            const test2 = { match_id: 1, profile_id: 2, like: "pending" };

            // Créer un match
            const createMatch = await Match.create();

            // Créer les match_profiles
            await Match_Profile.create(test2);
            console.log('Match_Profile créé pour Profile 1:', await Match_Profile.findOne({ where: { match_id: createMatch.id, profile_id: 1 } }));

            await Match_Profile.create(test1);
            console.log('Match_Profile créé pour Profile 2:', await Match_Profile.findOne({ where: { match_id: createMatch.id, profile_id: 2 } }));

            res.status(200).json(createMatch)

        } catch (error) {
            console.log(error.message)
            res.status(500).json({ error: error.message })
        };

I enabled Sequelize logging to see what's happening, and it adds two elements but without the match_id or profile_id:

Executing (default): INSERT INTO "match" ("id","status","created_at","updated_at") VALUES (DEFAULT,$1,$2,$3) RETURNING "id","status","created_at","updated_at","deleted_at";
Executing (default): INSERT INTO "match_profile" ("like","created_at","updated_at") VALUES ($1,$2,$3) RETURNING "like","created_at","updated_at";
Executing (default): SELECT "like", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "match_profile" AS "Match_Profile" WHERE "Match_Profile"."match_id" = 1 AND "Match_Profile"."profile_id" = 1 LIMIT 1;
Match_Profile créé pour Profile 1: null
Executing (default): INSERT INTO "match_profile" ("like","created_at","updated_at") VALUES ($1,$2,$3) RETURNING "like","created_at","updated_at";
Executing (default): SELECT "like", "created_at" AS "createdAt", "updated_at" AS "updatedAt" FROM "match_profile" AS "Match_Profile" WHERE "Match_Profile"."match_id" = 1 AND "Match_Profile"."profile_id" = 2 LIMIT 1;
Match_Profile créé pour Profile 2: null

I don’t understand why the foreign keys aren’t being added. I thought it might be an issue with my associations, but I don’t see any problems. Can you help me please? :)

I want to add fully elements of my controller in the join table match_profile

发布评论

评论列表(0)

  1. 暂无评论