Sequelize: Include.where filtering by a 'parent' Model attribute

前端 未结 3 1518
我在风中等你
我在风中等你 2021-02-05 05:47

I have two Models related, Catalog and ProductCategory. The latter has a composed PK, \'id, language_id\'. Here are the models simplified:

var Catalog = sequelize         


        
相关标签:
3条回答
  • 2021-02-05 05:58

    You can try this (Especially if you are using MariaDB) -

    const Sequelize = require('sequelize'); 
    const op = Sequelize.Op;
    
    Catalog.find({where:
        {id: itemId},
        include: {
            model: models.ProductCategory, 
            where: {
              language_id: {[op.col]: 'Catalog.language_id'}
            }
        }
    })
    
    0 讨论(0)
  • 2021-02-05 06:03

    This seems this do the trick:

    where: {language_id: models.sequelize.literal('Catalog.language_id')}
    
    0 讨论(0)
  • 2021-02-05 06:08

    Sequelize provides an extra operator $col for this case so you don't have to use sequelize.literal('...') (which is more a hack).

    In your example the usage would look like this:

    Catalog.find({where:
        {id: itemId},
        include: {
            model: models.ProductCategory, 
            where: {
              language_id: {$col: 'Catalog.language_id'}
            }
        }
    })
    
    0 讨论(0)
提交回复
热议问题