sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

[Question] Misunderstood setting relation

Open cybernadinou opened this issue 11 years ago • 1 comments

Hi everybody,

I'm reading the documentation and try some stuff but maybe I made a mistake or something that I don't understand :/ What is the difference between this :

return  sequelize.define("Don",{
        id :{
            primaryKey      : true,
            autoIncrement   : true,
            type            : DataTypes.INTEGER,
            allowNull       : false
        },
        idUser :{
            field           : 'id_user',
            type            : DataTypes.INTEGER,
            allowNull       : false,
            references: "user",
            referenceKey: "id",
            validate:{
                notNull     : true,
                isInt       : true
            }
        },
       {
        tableName : 'don',
        timestamps: true,
        createdAt: "created_at",
        updatedAt: "updated_at",
        deletedAt: "deleted_at",
        paranoid: true
    });

In this example I got my foreignKey when I define my model but we can do this thing for example :

    m.user.hasMany(m.don, { foreignKey: 'id_user' });
    m.don.belongsTo(m.user,{ foreignKey: 'id_user' });

So what the difference ? And btw is it normal when I don't put inside my model the attributes references and referenceKey and I'm using the hasMany he don't care about my allowNull : false from my model.

Thanks for your answer / help, Best regards

cybernadinou avatar Jun 30 '15 18:06 cybernadinou

foreignKey on an association defines what attribute we should use to store the value in. In your case they should point at your attribute name idUser instead of the field name.

It's perfectly fine to put references on the model options rather than on the association options.

Closing since neither a bug or a feature request, but you are welcome to keep posting in this issue :)

mickhansen avatar Jul 01 '15 07:07 mickhansen