hasMany relation: including from the other direction

天涯浪子 提交于 2019-12-08 02:55:41

问题


Say I have the next model:

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

A.k.a. a user might have many invoices. This code adds the field receiverId to the invoice model.

Now I want to get a list of invoices including their receivers. How can I do that?

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

Or

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

Did not work, returned: "Relation \"receiver\" is not defined for Invoice model" error.

Thanks for your help.


回答1:


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);
});


来源:https://stackoverflow.com/questions/30840146/hasmany-relation-including-from-the-other-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!