Sequelize Create method does not insert an object field

Asked

Viewed 475 times

-1

I am making an application with Sequelize, and when I run the model.create({obj}) function, one of the fields is not inserted in the database. The field in question is a Foreign key from another table. The table in question has two primary keys from this second table. One is being inserted, the other is just not. Follows code:

I put only the code that has to do with the routine in question.

AppointmentController.js
class AppointmentController {
async store(req, res) {
    // Schemas validation
    const schema = Yup.object().shape({
        provider_id: Yup.number().required(),
        date: Yup.date().required(),
    });

    if (!(await schema.isValid(req.body))) {
        return res.status(400).json({
            erro: "validation fails",
        });
    }

    const { provider_id, date } = req.body;


    const appointment = await Appointment.create({
        user_id: req.userId,
        provider_id,
        date,
    });

    return res.json(appointment);
}
}

Table model:

class Appointment extends Model {
static init(sequelize) {
    super.init(
        {
            date: Sequelize.DATE,
            canceledAt: Sequelize.DATE,
        },
        { sequelize }
    );

    return this;
}

static associate(models) {
    this.belongsTo(models.User, { as: "user", foreignKey: "user_id" });
    this.belongsTo(models.User, { as: "provider", foreignKey: "user_id" });
}
}

The Migration of the table:

module.exports = {
up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("appointments", {
        id: {
            type: Sequelize.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
        },
        date: {
            allowNull: false,
            type: Sequelize.DATE,
        },
        user_id: {
            type: Sequelize.INTEGER,
            references: { model: "users", key: "id" },
            onUpdate: "CASCADE",
            onDelete: "SET NULL",
            allowNull: true,
        },
        provider_id: {
            type: Sequelize.INTEGER,
            references: { model: "users", key: "id" },
            onUpdate: "CASCADE",
            onDelete: "SET NULL",
            allowNull: true,
        },
        canceled_at: {
            type: Sequelize.DATE,
            allowNull: true,
        },
        created_at: {
            type: Sequelize.DATE,
            allowNull: false,
        },
        updated_at: {
            type: Sequelize.DATE,
            allowNull: false,
        },
    });
},

down: queryInterface => {
    return queryInterface.dropTable("appointments");
},
};

Example of my request:

{
"provider_id":18,
"date":"2020-03-05T18:00:00-03:00"
}

Return I’m getting:

{
"id": 81,
"user_id": 19,
"date": "2020-03-05T21:00:00.000Z",
"updatedAt": "2020-03-07T02:48:53.212Z",
"createdAt": "2020-03-07T02:48:53.212Z",
"provider_id": null,
"canceledAt": null
}

In the Vscode console I can see the query executed, and the function does not pass any value, nor put the column 'provider_id' in the Insert. Follows query:

INSERT INTO "appointments" ("id","date","created_at","updated_at","user_id") VALUES 
(DEFAULT,$1,$2,$3,$4) RETURNING *;

I’m pretty sure the problem is related to these two FK s using the same column of the Users table, but I haven’t been able to solve it yet.

1 answer

0

The problem was in my method of association I was passing the same foreign key in both references. I thought it needs to look like this, after all are two different references, however, the same column of the target table User.

I had to change the name from user_id to provider_id (which is actually the name of the column in the database).

How was:

 static associate(models) {
 this.belongsTo(models.User, { as: "user", foreignKey: "user_id" });
 this.belongsTo(models.User, { as: "provider", foreignKey: "user_id" });
 }
 }

How it worked out:

static associate(models) {
this.belongsTo(models.User, { as: "user", foreignKey: "user_id" });
this.belongsTo(models.User, { as: "provider", foreignKey: "provider_id" });
}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.