简体   繁体   中英

sequelize getAssociation for hasMany relation

Billing and Particular has 1:m relationship. so, Billing.hasMany(Particular, {as: 'particulars', foreignKey: 'billing_id'})

Now, I would like to grab one of the several particulars for given billing also make sure the billing exists in first place.

GET /api/billings/:billingId/particulars/:particularId

async function getParticular(req, res, next) {

    try {

    let billing;
    let result;

    billing = await Billing.findById(req.params.billingId);

    if(!billing) {
        throw new Error('Billing Not found');
    }

    result = await billing.getParticular(req.params.particularId);
    //Oh, wait, but billing.getParticular is not a function

    if(!result) {
        throw new Error('Particular Not found');
    }

    res.json(result);

    } catch (e) {
        next(e)
    }

}

How am I supposed to grab one of many particulars?

The method you are looking for is getParticulars , which returns list of related model instances basing on where attribute of passed options

result = await billing.getParticulars({ where: { id: req.params.particularId } });

result would be an array of particulars having id = 1 , so probably single element array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM