How to join the tables on the custom fields in Sequelize JS

2,195 views
Skip to first unread message

Alexey Prokoptsev

unread,
Dec 5, 2015, 4:17:21 PM12/5/15
to Sequelize

HI.I have some difficulty with usage sequelize.js. There are the following data model (simplified):
  
var Organization = sequelize.define('organization', {
  organizationRegId
: {
    type
: Sequelize.STRING(250),
    field
: "organizationregid",
 
}
});

var Person = sequelize.define('person', {
  organization
: {
    type
: Sequelize.STRING(250),
    field
: "organizationid",
 
}
});

Need to get all users whose identifier (organizationregid) intersects with the organization identifier in the organization (organizationid).
In sql query looks like this:
   
SELECT * FROM persons AS p LEFT JOIN organizations AS o ON p.organizationid = o.organizationregid;

I can't change data schema.
I'm experimented with hasMany, but failed.

Mick Hansen

unread,
Dec 5, 2015, 4:28:52 PM12/5/15
to Alexey Prokoptsev, Sequelize
Please add your association setup aswell.
Is organizationregid not the primary key? 
hasMany only supports mapping from a foreign key to a primary key, not from a foreign key to an arbitrary column
--
Mick Hansen
@mhansendev
mhansen.io

Alexey Prokoptsev

unread,
Dec 5, 2015, 5:55:51 PM12/5/15
to Sequelize, a.prok...@gmail.com
Problem is that the models are not related directly(If I understand you correctly). I need to attach organizations to the person which person.organizationid equal organization.organizationregid.

Yes, organizationregid isn't the primary key

воскресенье, 6 декабря 2015 г., 0:28:52 UTC+3 пользователь Mick Hansen написал:

Mick Hansen

unread,
Dec 6, 2015, 8:09:59 AM12/6/15
to Alexey Prokoptsev, Sequelize
Sequelize does not support non primary key relations for hasMany.
So if your two models are not related by a primary key and they need to be 1:M you'll have to do it manually at the moment.

Alexey Prokoptsev

unread,
Dec 6, 2015, 1:04:34 PM12/6/15
to Sequelize, a.prok...@gmail.com
Ok.

Could you show an example for  manually query?

воскресенье, 6 декабря 2015 г., 16:09:59 UTC+3 пользователь Mick Hansen написал:

Mick Hansen

unread,
Dec 6, 2015, 2:39:07 PM12/6/15
to Alexey Prokoptsev, Sequelize
First query the organization, then query for persons with a where based on values from that organization.
Reply all
Reply to author
Forward
0 new messages