Skip to content

Include on through association #10828

Closed

Description

@njdart

What are you doing?

I have two models, Patient, and Device that are linked through a reference table PatientDevice. The linking table also contains references to the User table about who made changes to the associations (createdBy, updatedBy, etc). When I use an include within
the through block of a query, it results in a Cannot read property 'indexOf' of undefined error

'use strict';

const Sequelize = require('sequelize');

const sequelize = new Sequelize('test', 'postgres', 'postgres', {
    dialect: 'postgres'
});

(async function() {
    await sequelize.authenticate();

    const User = sequelize.define('user', {
        name: Sequelize.STRING
    });

    const Patient = sequelize.define('patient', {
        name: Sequelize.STRING
    });

    const Device = sequelize.define('device', {
        serial: Sequelize.STRING
    });

    const PatientDevice = sequelize.define('patientDeviceAssociation', {
        patient: {
            type: Sequelize.INTEGER,
            foreignKey: {
                references: Patient
            }
        },
        device: {
            type: Sequelize.INTEGER,
            foreignKey: {
                references: Device
            }
        },
        createdBy: {
            type: Sequelize.INTEGER,
            foreignKey: {
                references: User
            }
        },
        updatedBy: {
            type: Sequelize.INTEGER,
            foreignKey: {
                references: User
            }
        }
    });

    Device.belongsToMany(Patient, {
        through: PatientDevice,
        foreignKey: 'device',
        otherKey: 'patient'
    });

    PatientDevice.belongsTo(User, {
        as: 'creator',
        foreignKey: 'createdBy'
    });

    PatientDevice.belongsTo(User, {
        as: 'updater',
        foreignKey: 'updatedBy'
    });

    await sequelize.sync({force: true});

    const user = await User.create({name: 'Dr. Jimmie'});
    const device = await Device.create({serial: '1234'});
    const patient = await Patient.create({name: 'Sick Doris'});
    await device.addPatient(patient, {through: {createdBy: user.id, updatedBy: user.id}});

    // This does not return the creator or updater users
    const foundDevice = await Device.findOne({
        where: { serial: '1234' },
        include: [
            { all: true, nested: true }
        ]
    });
    console.dir(foundDevice.toJSON(), {depth: null});

    // this does return the association
    const foundAssociation = await PatientDevice.findOne({include: [ {all: true, any: true}]});
    console.dir(foundAssociation.toJSON(), {depth: null});

    // This causes the crash and exception below
    const foundDevice2 = await Device.findOne({
        where: { serial: '1234' },
        include: [
            {
                model: Patient,
                through: {
                    // commenting out the include property stops the crash
                    include: [
                        {
                            model: User,
                            as: 'creator'
                        },
                        {
                            model: User,
                            as: 'updater'
                        }
                    ]
                }
            }
        ]
    });
    console.dir(foundDevice2.toJSON(), {depth: null});
    await sequelize.close();
})();

What do you expect to happen?

(if it works) A response containing the creator and updater associations, or (if it doesn't work) no exception to be thrown and the include in the through to be ignored

// const device = ...
{
    id: 1,
    serial: '1234',
    createdAt: '2019 - 04 - 23T11: 42: 53.364Z',
    updatedAt: '2019 - 04 - 23T11: 42: 53.364Z',
    patients:
        [{
            id: 1,
            name: 'Sick Doris',
            createdAt: '2019 - 04 - 23T11: 42: 53.369Z',
            updatedAt: '2019 - 04 - 23T11: 42: 53.369Z',
            patientDeviceAssociation:
            {
                patient: 1,
                device: 1,
                createdBy: 1,
                updatedBy: 1,
                createdAt: '2019 - 04 - 23T11: 42: 53.382Z',
                updatedAt: '2019 - 04 - 23T11: 42: 53.382Z',
                creator:
                {
                    id: 1,
                    name: 'Dr. Jimmie',
                    createdAt: '2019 - 04 - 23T11: 42: 53.345Z',
                    updatedAt: '2019 - 04 - 23T11: 42: 53.345Z'
                },
                updater:
                {
                    id: 1,
                    name: 'Dr. Jimmie',
                    createdAt: '2019 - 04 - 23T11: 42: 53.345Z',
                    updatedAt: '2019 - 04 - 23T11: 42: 53.345Z'
                }
            },
        }]
}

What is actually happening?

(node:6746) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of undefined
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3473:80)
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3444:18)
    at model._initValues (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:169:10)
    at new Model (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:114:10)
    at new patientDeviceAssociation (/home/nic/playground/sequelize/node_modules/sequelize/lib/sequelize.js:357:19)
    at Function.build (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:2140:12)
    at model._setInclude (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3607:85)
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3475:14)
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3444:18)
    at model._initValues (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:169:10)
    at new Model (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:114:10)
    at new patient (/home/nic/playground/sequelize/node_modules/sequelize/lib/sequelize.js:357:19)
    at Function.build (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:2140:12)
    at valueSets.map.values (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:2160:41)
    at Array.map (<anonymous>)
    at Function.bulkBuild (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:2160:22)
    at model._setInclude (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3610:83)
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3475:14)
    at setKeys (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3432:20)
    at model.set (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:3440:13)
    at model._initValues (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:169:10)
    at new Model (/home/nic/playground/sequelize/node_modules/sequelize/lib/model.js:114:10)

This seems to be the line that caused the issue

Environment

Dialect:

  • mysql
  • postgres 10.6 (docker postgres:10.6)
  • sqlite
  • mssql
  • any

Dialect library version: pg-native 3.0.0, pg 7.10.0
Database version: 10.6
Sequelize version: 5.7.4
Node Version: 8.12.0
OS: Arch Linux (both native and within docker node:carbon-alpine)

Tested with latest release:

  • No
  • Yes, specify that version: 5.7.4

Activity

  1. SimonSchick commented on Apr 23, 2019

    @SimonSchick
  2. njdart commented on Apr 23, 2019

    @njdart
    Author

    @SimonSchick Thanks for the quick response.

    I applied the diff, but it hasn't changed the error i was getting, although I am using postgres not mysql. I couldn't find an equivalent bit in lib/dialects/postgres/query.js. Any advice?

  3. SimonSchick commented on Apr 23, 2019

    @SimonSchick
    Contributor

    Uhh, I think I posted this in the wrong issue 😅

  4. njdart commented on Apr 24, 2019

    @njdart
    Author

    I ended up working around this by searching for the joining table, including the models, and applying the where on that model's include.

    It doesn't read quite as nice as I would like, but it works.

    'use strict';
    
    const Sequelize = require('sequelize');
    
    const sequelize = new Sequelize('postgres', 'postgres', 'postgres', {
        dialect: 'postgres'
    });
    
    (async function() {
        await sequelize.authenticate();
    
        const User = sequelize.define('user', {
            name: Sequelize.STRING
        });
    
        const Patient = sequelize.define('patient', {
            name: Sequelize.STRING
        });
    
        const Device = sequelize.define('device', {
            serial: Sequelize.STRING
        });
    
        const PatientDevice = sequelize.define('patientDeviceAssociation', {
            patientId: Sequelize.INTEGER,
            deviceId: Sequelize.INTEGER,
            createdBy: Sequelize.INTEGER,
            updatedBy: Sequelize.INTEGER
        });
    
        Device.belongsToMany(Patient, {
            through: PatientDevice,
            foreignKey: 'deviceId',
            otherKey: 'patientId'
        });
    
        Patient.belongsToMany(Device, {
            through: PatientDevice,
            foreignKey: 'patientId',
            otherKey: 'deviceId'
        });
    
        PatientDevice.belongsTo(Patient, {
            foreignKey: 'patientId'
        });
    
        PatientDevice.belongsTo(Device, {
            foreignKey: 'deviceId'
        });
    
        PatientDevice.belongsTo(User, {
            as: 'creator',
            foreignKey: 'createdBy'
        });
    
        PatientDevice.belongsTo(User, {
            as: 'updater',
            foreignKey: 'updatedBy'
        });
    
        await sequelize.sync({force: true});
    
        const user = await User.create({name: 'Dr. Jimmie'});
        const device = await Device.create({serial: '1234'});
        const patient = await Patient.create({name: 'Sick Doris'});
        await device.addPatient(patient, {through: {createdBy: user.id, updatedBy: user.id}});
    
        const foundAssociation2 = await PatientDevice.findAll({
            include: [
                Patient,
                {
                    model: Device,
                    where: {
                        serial: '1234'
                    }
                },
                {
                    model: User,
                    as: 'creator'
                },
                {
                    model: User,
                    as: 'updater'
                }
            ]
        });
        console.dir(foundAssociation2.map(el => el.toJSON()), {depth: null});
        /*
        [{
            patientId: 1,
            deviceId: 1,
            createdBy: 1,
            updatedBy: 1,
            createdAt: '2019 - 04 - 24T12: 37: 07.259Z',
            updatedAt: '2019 - 04 - 24T12: 37: 07.259Z',
            patient:
            {
                id: 1,
                name: 'Sick Doris',
                createdAt: '2019 - 04 - 24T12: 37: 07.247Z',
                updatedAt: '2019 - 04 - 24T12: 37: 07.247Z'
            },
            device:
            {
                id: 1,
                serial: '1234',
                createdAt: '2019 - 04 - 24T12: 37: 07.240Z',
                updatedAt: '2019 - 04 - 24T12: 37: 07.240Z'
            },
            creator:
            {
                id: 1,
                name: 'Dr. Jimmie',
                createdAt: '2019 - 04 - 24T12: 37: 07.223Z',
                updatedAt: '2019 - 04 - 24T12: 37: 07.223Z'
            },
            updater:
            {
                id: 1,
                name: 'Dr. Jimmie',
                createdAt: '2019 - 04 - 24T12: 37: 07.223Z',
                updatedAt: '2019 - 04 - 24T12: 37: 07.223Z'
            }
        }]
        */
    
        await sequelize.close();
    })();
  5. olafwrieden commented on May 7, 2019

    @olafwrieden

    @njdart I am facing the very same issue. In my case, a User belongs to many Accounts through a AccountUser table. However, a user could be of various roles in the relation (Admin, Owner, etc) which are defined in another table. I too tried the include in the same way you have and get Cannot read property 'includes' of undefined error.
    I would think this is a common use case and spent about a week and a half trying to get it working. No luck. Is someone from the Sequelize.js community addressing this? It's clearly an issue.

  6. papb commented on Aug 1, 2019

    @papb
    Member

    It is possible to do this already, but it requires a little 'trick'. I plan on documenting it in the near future. Please hang on just a little longer 😬

    If you do not hear from me after a while feel free to call my attention on this again.

  7. added
    status: understood
    docs
    on Aug 1, 2019
  8. self-assigned this
    on Aug 1, 2019
  9. added
    status: wip
    and removed
    status: understood
    on Sep 6, 2019
  10. removed
    status: wip
    on Jan 15, 2020
  11. cristianszwarc commented on Apr 25, 2020

    @cristianszwarc

    @papb thanks for your amazing work with the documentation.

    might you please elaborate on "but it requires a little 'trick'"? already went through your PR multiple times but still trying to find out how to include associations to the linking/through record.

    thanks!

  12. ridakk commented on Jun 26, 2020

    @ridakk

    @papb i have been searching for the same thing how to include on through, could you please show the trick you mentioned?

  13. mjy78 commented on Jul 22, 2020

    @mjy78
    Contributor

    Would also love to know the secret @papb :)

  14. osminosm commented on Jul 24, 2020

    @osminosm
  15. osvaldokalvaitir commented on Jul 29, 2020

    @osvaldokalvaitir

    I am wondering how it includes too, has it been resolved?

  16. muhammadfazeel commented on Nov 23, 2020

    @muhammadfazeel

    has it been resolved?

  17. eperezf commented on Nov 29, 2020

    @eperezf

    I'm having the same issue. The StackOverflow issue is not related.

    @papb where can we see the solution?

  18. fraywing commented on Dec 8, 2020

    @fraywing

    @papb @sushantdhiman any movement on this? This should be a totally legal thing to do.

  19. techuila commented on Feb 25, 2021

    @techuila

    any update on this?

  20. Nakroma commented on Feb 26, 2021

    @Nakroma

    also wondering - am in need of this

  21. osvaldokalvaitir commented on Feb 27, 2021

    @osvaldokalvaitir

    me too

  22. Nakroma commented on Feb 28, 2021

    @Nakroma

    A workaround that I'm using right now is having the through table as its own standalone one with 1:N relationships between the two M:N tables.

  23. techuila commented on Feb 28, 2021

    @techuila

    @Nakroma same.

    but it would be really nice if it's possible to include on through associations.

  24. pulsovi commented on May 27, 2021

    @pulsovi

    I'm having the same issue. The StackOverflow issue is not related.

    @papb where can we see the solution?

    Hello all,

    I have the same issue, I came across this page which pointed me in the right direction, thank you all.

    I think @papb is talking about this: https://sequelize.org/master/manual/advanced-many-to-many.html#through-tables-versus-normal-tables-and-the--quot-super-many-to-many-association-quot-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

docs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions