One to Many relation on Foreign Key column - Postgres 9.5.3
See original GitHub issueI’m having issues setting up the relations for a one to many relationship where the “many" table references the “one” table through a non-primary key column on the “one” table. The schema has already been predetermined, so I’m not able to edit it at all.
Postgres v9.5
Here’s the models:
var Offer = sequelize.define(‘offer’,{ id: { type: Sequelize.INTEGER, primaryKey: true, allowNull: false, field: "id" }, otherid:{ type: Sequelize.STRING, allowNull: false, field: “otherid" });
var Attachment = sequelize.define(‘attachment’,{ id: { type: Sequelize.INTEGER, primaryKey: true, allowNull: false, field: "id" }, otherid:{ type: Sequelize.STRING, allowNull: false, field: “otherid" }, parentid:{ type: Sequelize.STRING, allowNull: true, field: "parentid", references: { model: Offer, key: "otherid" } } )
Each Offer should have many Attachments.
I set up the relations like this:
Attachment.belongsTo(Offer, {foreignKey:'parentid', targetKey:’otherid'});
Offer.hasMany(Attachment, {as: 'Attachments',foreignKey:'otherid'});
I know the Attachment.belongsTo relation is set up correctly, since I’m able to query for it and get the related Offer object returned:
attachments.findOne({ include: [ {model: m_offerCreatives} ] })
However, when I go to find the Offers, I get an error saying they aren’t related:
Offer.findAll({ include: [ {model: Attachment, as:'Attachments'} ]})
Error: “attachment (Attachments) is not associated to offer!”
I’ve tried setting this up every way I can think of from the docs, including defining Offer.belongsToMany(Attachment), but since there is no join table, I can’t seem to get it correct. I tried to do something similar for a Many-to-Many relationship with a join table that stores non-primary keys, but wasn’t able to get that to work either (I think it was the same issue in #4092).
Is it possible to have this one-to-many relationship on a non-primary key column?
Thanks!
Dialect: postgres Database version: 9.5.3 Sequelize version: 3.16
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (3 by maintainers)
@felix yes, but it’s broken for belongs to many (have to get that fixed soon)…
@jessedavid you need target key on both sides of the association
I added the targetKey but still got the same error and the SQL doesn’t look like it updated:
(SQL the same)
I’m using Typescript and the interface definition for hasMany doesn’t seem to have “targetKey” defined (not sure if this is a typings error or not).