简体   繁体   English

将hasAssociation序列化为hasMany关系

[英]sequelize getAssociation for hasMany relation

Billing and Particular has 1:m relationship. Billing and Particular具有1:m关系。 so, Billing.hasMany(Particular, {as: 'particulars', foreignKey: 'billing_id'}) 因此, 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 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 您正在寻找的方法是getParticulars ,它基于传递的options where属性返回相关模型实例的列表。

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

result would be an array of particulars having id = 1 , so probably single element array. result将是id = 1的详细信息数组,因此可能是单个元素数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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