Роман Парадеев Роман Парадеев - 11 months ago 64
Javascript Question

Combine model's condition with its association's condition in Sequelize

Is there a way to find models by a condition that applies to its own field or to its association's field?

Given models

Model
and
Association
, where each
Model
has one
Association
.

const Model = sequelize.define('model', {
name: sequelize.STRING,
});

const Association = sequelize.define('association', {
name: sequelize.STRING,
});

Association.belongsTo(Model);
Model.hasOne(Association);


I want to find all
Model
s, that either has a
name
equal to "text", or has an
Association
with a
name
equal to "text".

So far I come up with the solution with
Sequelize.literal
, that doesn't look robust enough.

Model.findAll({
attributes: ['id', 'name'],
include: [{
model: Association,
attributes: [],
}],
where: {
$or: [
{ name: 'test' },
Sequelize.literal('association.name = \'test\''),
],
},
});


Is there a better way?

Answer Source

This feature is described in the docs: Top level where with eagerly loaded models.

Model.findAll({
    attributes: ['id', 'name'],
    include: [{
        model: Association,
        attributes: [],
    }],
    where: {
        $or: [
            { name: 'test' },
            { '$association.name$':  'test' },
        ],
    },
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download