Reputation: 25284
I can't seem to get this to work.
I have two tables, AnalyticsSession and AnalyticsEvent and have tried to associate them.
When I query to get each Session and include the Events it works but the array is empty.
I wonder if I have the relationship correct?
The session
module.exports = (sequelize, DataTypes) => {
class AnalyticsSession extends Model {
static associate(models) {
AnalyticsSession.hasMany(models.AnalyticsEvent, {
foreignKey: "id",
});
}
}
AnalyticsSession.init(
{
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER(11).UNSIGNED,
},
},
{
sequelize,
modelName: "AnalyticsSession",
}
);
return AnalyticsSession;
};
The event
module.exports = (sequelize, DataTypes) => {
class AnalyticsEvent extends Model {
static associate(models) {
AnalyticsEvent.belongsTo(models.AnalyticsSession, {
foreignKey: "id",
sourceKey: "sessionId",
});
}
}
AnalyticsEvent.init(
{
id: {
type: DataTypes.INTEGER(11).UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
sessionId: {
allowNull: false,
foreignKey: true,
type: DataTypes.INTEGER(11).UNSIGNED,
references: {
model: "AnalyticsSession",
key: "id",
},
},
},
{
sequelize,
modelName: "AnalyticsEvent",
defaultScope: {},
}
);
return AnalyticsEvent;
};
The query
const sessions = await AnalyticsSession.findAll({
attributes: [
"id",
],
include: [
{
model: AnalyticsEvents,
attributes: ["id"],
},
],
logging: console.log,
});
Upvotes: 0
Views: 58
Reputation: 22783
You should indicate sessionId
as a foreignKey
option values because this field is a real foreign key field that points to AnalyticsSession
in AnalyticsEvent
:
AnalyticsSession.hasMany(models.AnalyticsEvent, {
foreignKey: "sessionId",
});
...
AnalyticsEvent.belongsTo(models.AnalyticsSession, {
foreignKey: "sessionId",
});
The sourceKey
by default is a primary key of 1 side in 1:N (i.e. a primary key of AnalyticsSession - id
field)
Upvotes: 1