Sunday, 2 April 2017

sequelize Nested include with where clause

I'm using sequelize for some filtering.

My current table structure:

  • Table1 holds Items (which has images) and Users (irrelevant)
  • Table1 has a direct relationship to Table2 (not to Table3)
  • Table2 has a direct relationship to Table3 (not to Table4)
  • Table3 has a direct relationship to Table4

I want to filter on Table3 and Table4 as well, considering I can only filter on Table2 using the top-level where-clause.

The way I fill out my where condition is just using a base object:

var Table2id       = parseInt(Table2id) || null,
    whereCondition = { deleted: 0 }

if (Table2id) { whereCondition['table2id'] = Table2id }
if (Table3id) { whereCondition['table3id'] = Table3id }
if (Table4id) { whereCondition['table4id'] = Table4id }

Table1.findAndCountAll({
        limit: limit,
        offset: offset,
        order: 'created_at DESC',
        where: whereCondition,
        include: [
            {
                model: User,
            }, {
                model: Item,
                include: [
                    {
                        model: Image
                    }
                ]
            }, {
                model: Table2,
                include: [
                    {
                        model: Table3,
                        include: [
                            {
                                model: Table4,
                            }
                        ]
                    }
                ]
            }
        ],
}).then(function (results) { res.json(results) })

I tried using some hacks I discovered like whereCondition['$Table3.table3id$'] = Table3id but to no avail.

How can I filter on nested includes? Is there another way I can structure the query so I don't have to have nested includes, but still retain this data structure (is there even a better way to structure this than what I've thought of)?



via NicT

No comments:

Post a Comment