hasMany关系:包括从另一个方向

时间:2015-06-15 08:03:54

标签: node.js strongloop loopback

说我有下一个型号:

user.json:
{//...
    "relations":{
        "invoices": {
            "type": "hasMany",
            "model": "Invoice",
            "foreignKey": "receiverId"
        },
    }
//...
}

A.k.a。用户可能有很多发票。此代码将字段receiverId添加到发票模型中。

现在我想获得一张包括收件人在内的发票清单。我怎么能这样做?

Invoice.find({include: "reciever"})

或者

Invoice.find({include: "user"})

无法正常工作,返回:“没有为发票模型定义”关系\“接收器\”错误。

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

You have to define belongsTo relation in your Invoice model.

invoice.json:

{//...
    "relations":{
        "receiver": {
            "type": "belongsTo",
            "model": "Receiver"
        },
    }
//...
}

Then you can query your model like this:

Invoice.find({include: "receiver"}, function(data){ 
   console.log(data);
});