Trying to display a nested relationship:
Cat.hasMany(legs)
Leg.belongsTo(cat)
Leg.hasOne(paw)
paw.hasMany(leg)
This is the Cat Model:
module.exports = (sequelize, DataTypes) => {
const Cat = sequelize.define('Cat', {
userId: {
type: DataTypes.STRING,
},
}, {});
Cat.associate = function (models) {
Cat.hasMany(models.Leg, {
foreignKey: 'catId',
as: 'legs',
});
};
return Cat;
};
The Legs Model:
module.exports = (sequelize, DataTypes) => {
const Leg = sequelize.define('Leg', {
originalValue: DataTypes.JSON,
newValue: DataTypes.JSON,
legId: DataTypes.INTEGER,
objectId: DataTypes.INTEGER,
pawId: DataTypes.INTEGER,
}, {});
Leg.associate = function (models) {
Leg.belongsTo(models.Cat, {
foreignKey: 'LegId',
onDelete: 'CASCADE',
});
Leg.hasOne(models.Paw, {
foreignKey: 'pawId',
});
};
return Leg;
};
The Paw model
module.exports = (sequelize, DataTypes) => {
const Paw = sequelize.define('Paw', {
pawType: DataTypes.STRING,
}, {});
Paw.associate = function (models) {
Paw.hasMany(models.Leg, {
foreignKey: 'pawId',
as: 'paws',
});
};
return Paw;
};
When querying the Cat Table, the code currently displays:
[
{
"id": 1,
"userId": "2wdfs",
"createdAt": "2018-04-14T20:12:47.112Z",
"updatedAt": "2018-04-14T20:12:47.112Z",
"legs": [
{
"id": 1,
"catId": 1,
"pawId": 1,
"createdAt": "2018-04-14T20:12:54.500Z",
"updatedAt": "2018-04-14T20:12:54.500Z"
}
]
}
]
I want to include the pawType from the paws table like this:
[
{
"id": 1,
"userId": "2wdfs",
"createdAt": "2018-04-14T20:12:47.112Z",
"updatedAt": "2018-04-14T20:12:47.112Z",
"legs": [
{
"id": 1,
"catId": 1,
"paws" : [
{
"id": 1,
"pawType": "cute"
}
],
"createdAt": "2018-04-14T20:12:54.500Z",
"updatedAt": "2018-04-14T20:12:54.500Z"
}
]
}
]
Query used to retrieve Cats:
return Cat.findAll({ include: [{ model: Leg, as: 'legs',include [{model: Paw,}], }], })
Error received:
{ SequelizeDatabaseError: column legs->Paw.pawId does not exist
{ error: column legs->Paw.pawId does not exist
Full SQL command:
sql: 'SELECT "Cat"."id", "Cat"."userId", "Cat"."createdAt", "Cat"."updatedAt", "legs"."id" AS "legs.id", "legs"."originalValue" AS "legs.originalValue", "legs"."newValue" AS "legs.newValue", "legs"."catId" AS "legs.catId", "legs"."objectId" AS "legs.objectId", "legs"."pawId" AS "legs.pawId", "legs"."createdAt" AS "legs.createdAt", "legs"."updatedAt" AS "legs.updatedAt", "legs->Paw"."id" AS "legs.Paw.id", "legs->Paw"."paw" AS "legs.Paw.paw", "legs->Paw"."pawId" AS "legs.Paw.pawId", "legs->Paw"."createdAt" AS "legs.Paw.createdAt", "legs->Paw"."updatedAt" AS "legs.Paw.updatedAt" FROM "Cats" AS "Cat" LEFT OUTER JOIN "Legs" AS "legs" ON "Cat"."id" = "legs"."catId" LEFT OUTER JOIN "Paws" AS "legs->Paw" ON "legs"."id" = "legs->Paw"."pawId";' },