Svarog
Svarog

Reputation: 2208

hasMany relation: including from the other direction

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.

Upvotes: 1

Views: 389

Answers (1)

A.Z.
A.Z.

Reputation: 1648

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

Upvotes: 4

Related Questions