Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize where condition for nested models

I have a database with notes and users.Now i want to get all notes where note content = something or users.name = something.I can write this query easily with SQL but couldn't get it working with sequlizer.

Note.findAll({
   include: [
             { model: Users, where: { name: 'something' }}
    ]
})

expected query is

select * from users,notes where notes.content='something' or users.name='something'

The issue is Note is not inside include so I cannot use

where: {
     '$or':{

My question is how to have where with or condition on nested table using sequelize

like image 500
while true Avatar asked Apr 21 '26 19:04

while true


1 Answers

Note.findAll({
    where: {
        [Op.or]: [
            { content: { [Op.like]: 'something' } },
            { '$users.name$': { [Op.like]: 'john' } },
        ]
    },
    include: [
        { model: Users, as: 'users', required: true }
    ]
})
like image 194
Yang Yu Avatar answered Apr 24 '26 09:04

Yang Yu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!