Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Join on Non Primary Key

I have two tables I need to associate. TableA has One TableB. I'm able to do this in the TableA Model:

TableA.hasOne( models.TableB, { as: 'TableB', foreignKey: 'someID' } );

Looking at the SQL, this tries to join TableA.ID and TableB.someID. What I actually want, is to join TableA.someNonPrimaryKey and TableB.someID.

How can I tell sequelize to join with someNonPrimaryKey?

like image 760
KJ3 Avatar asked Mar 10 '15 21:03

KJ3


2 Answers

I know this is old; I am responding for the sake of others that might need the answer.

You can now associate tables on non-primary key columns. In your case, the association would be:

TableA.hasOne(TableB, {
  sourceKey: 'someNonPrimaryKeyColumnOnTheSOurceModel',
  foreignKey: 'matchingColumnOnTheTargetModel'
});

Please note, the column someNonPrimaryKeyColumnOnTheSOurceModel must have unique set to true in the model definition.

You can read more about it here: https://sequelize.org/master/manual/assocs.html

like image 70
King James Enejo Avatar answered Sep 28 '22 03:09

King James Enejo


For me it worked by doing both answers above from @thanh1101681 and @King James Enejo, only putting either sourcekey or targetkey didn't work!

TableB.belongsTo(models.TableA, { foreignKey: 'someID', targetKey: 'notTableAID' } );

TableA.hasOne(TableB, {
  sourceKey: 'someNonPrimaryKeyColumnOnTheSOurceModel',
  foreignKey: 'matchingColumnOnTheTargetModel'
});
like image 26
Hina Avatar answered Sep 28 '22 02:09

Hina