Reputation: 33
I have a database storing users from two different platforms.
In one table, let's say we have a table called platformA
that holds id
, platformAid
, username
.
In the second table, let's say we have a table called platformB
that holds id
, platformBid
, username
, level
.
Now, I want to create another table to "link" the two accounts together using the primary key from both platforms. The table will ideally be like so: id
, platformAid
, platformBid
.
So, I have the database models defined like this
var platformA = db.define('platformA', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
platformAid: { type: Sequelize.INTEGER },
username: { type: Sequelize.CHAR }
});
var platformB = db.define('platformB', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
platformBid: { type: Sequelize.INTEGER },
username: { type: Sequelize.CHAR },
level: { type: Sequelize.INTEGER }
});
var connect = db.define('connect ', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
platformAid: {
type: Sequelize.INTEGER,
refrences: {
model: 'platformA',
key: 'id'
}
},
platformBid: {
type: Sequelize.INTEGER,
refrences: {
model: 'platformB',
key: 'id'
}
},
});
As far as I know, I then need to use belongsTo
like so
platformA.belongsTo(connect, { foreignKey: 'id', as: 'platformAid' });
platformB.belongsTo(connect, { foreignKey: 'id', as: 'platformBid' });
Now this code creates the tables just fine, however there's no foreign keys to be found. At this point, I probably have something backwards or am missing something. Any help would be appreciated!
Upvotes: 0
Views: 70
Reputation: 7401
You are doing the connection in wrong way.
platformA.belongsTo(connect, { foreignKey: 'id', as: 'platformAid' });
Above code states that the field id
in table platformA
references table connect
, whereas the id
field should be a primary key of platformA
. The as
attribute only defines alias
for the association, not the field.
In order to define the foreign key on connect
table that reference models platformA
and platformB
you need to define the association on connect
model
connect.belongsTo(platformA, { foreignKey: 'platformAid', as: 'platformA' });
This association states that the platformAid
column in connect
table references platformA
table. Then you need to do the same with platformB
connect.belongsTo(platformB, { foreignKey: 'platformBid`, as: 'platformB' });
That is where my comment comes from - do you want to create a m:n relation between platformA
and platformB
, because that is when the join table is being used, just as in your case.
Upvotes: 1