Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie füge ich Bedingungen in Sub-Sub-Kindmodellen in Sequelize hinzu, die sich auf mein übergeordnetes Modell in findAndCountAll auswirken sollen?

Okay, ich habe die Lösung gefunden, aber eine Rohabfrage mit Joins hinzugefügt, in der ich meine erforderlichen Bedingungen hinzugefügt habe, wo immer ich sie brauchte, und IDs des Hauptmodells abgerufen habe. Dann habe ich die Daten mit sequelize abgerufen und diese IDs in der where-Klausel hinzugefügt. Mein Code sieht jetzt so aus.

const { limit, offset } = dbHelpers.GetPagination(
    req.query.limit,
    req.query.offset
);

let querySting = "(SELECT count(DISTINCT p.id) FROM ModelA p " +
    "JOIN ModelB cp ON cp.pId = p.id " +
    "JOIN ModelC cs ON cs.cpId = cp.id " +
    "JOIN ModelD ms ON ms.csId = cs.id " +
    "LEFT JOIN ModelE sa ON sa.msId = ms.id " +
    "LEFT JOIN ModelF pp ON pp.msId = ms.id " +
    "LEFT JOIN ModelG sta ON sta.ppId = pp.id " +
    "LEFT JOIN ModelH ol ON ol.cdId = cd.id " +
    "WHERE "   //you can add your conditions here
    + " ORDER BY p.id desc LIMIT  " + offset + ",  " + limit + ")"


const rawQuery = await models.sequelize.query(querySting,
    { type: QueryTypes.SELECT })
const Ids = rawQuery.map(result => result.id)

const results = await models.ModelA.findAndCountAll({
    where: {
        id: Ids
    },
    include: [
        {
            model: models.ModelB,
            as: "ModelB",
            include: [
                {
                    model: models.ModelC,
                    separate: true,
                },
                {
                    model: models.ModelD,
                    separate: true,
                    include: [
                        {
                            model: models.ModelE,
                            separate: true,
                                            {
                            model: models.ModelF,
                            separate: true,
                        },
                    ],
                },
            ],
        },
    ],
},
    {
        model: models.ModelG,
        include: [
            {
                model: models.ModelH,
                as: "ModelH",
            },
        ],
    },
                ],
            });