hasMany relation: including from the other direction

389 views Asked by At

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

There are 1 answers

0
A.Z. On BEST ANSWER

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