Search code examples
node.jsjoinsequelize.jsassociations

Is there a way to associate one table's an attribute to another table's any attribute in Sequelize?


There is a table called Order, Order has PK (id) and an attribute (company_id).

Other table is Company_Parameter that has PK(Id) and an attribute (cid).

I want to connect these tables on Order.company_id = Company_Parameter.cid but company_id and cid are not primary keys.

I have set an association like this in sequelize:

Order.hasMany(companyParameters, { foreignKey: 'cid', targetKey: 'company_id', }); companyParameters.belongsTo(Order, { foreignKey: 'cid', targetKey: 'company_id', });

but these association run:

ON Order.id = companyParameters.cid;

I want to run

ON Order.company_id = companyParameters.cid;


Solution

  • In hasMany you should use the sourceKey option to indicate other model's key and not targetKey one.

    Order.hasMany(companyParameters, { foreignKey: 'cid', sourceKey: 'company_id', });