lewis4u
lewis4u

Reputation: 15057

Laravel 5.2 Model User->Invoice->InvoiceDetails

I have 3 models and i don't know which relationship do i need to write for each model

User | Invoice | InvoiceDetails

A User can have many Invoices and one Invoice is made by only one User. So in User Class i write:

public function invoice(){
    return $this->hasMany('App\Invoice');
}

and inside Invoice Class i write:

public function user(){
    return $this->belongsTo('App\User');
}

Is this ^ correct?

And now, one Invoice has one InvoiceDetail does that mean for each Invoice there is only one row in table invoice_details?

I just don't know what to write inside each model, how to connect them? I have made a little schema just to show what it should be like: enter image description here

So the question is, which functions to write inside each Model to declare proper connections between them?

Upvotes: 2

Views: 352

Answers (1)

Styphon
Styphon

Reputation: 10447

What you've written so far is fine, it links users to invoices properly (almost). The only thing is you need to rename owner_id to user_id, or specify that it should use the owner_id field.

User class

// Note that the function should be plural as it's for many
public function invoices(){
    return $this->hasMany('App\Invoice', 'owner_id', 'ID');
}

Invoice class

public function user(){
    return $this->belongsTo('App\User', 'ID', 'owener_id');
}

Then you just need to define the relationship with InvoiceDetails

Invoice class

public function invoiceDetails()
{
    return $this->hasMany('App\InvoiceDetails');
}

InvoiceDetails class

public function invoice()
{
    return $this->belongsTo('App\Invoice');
}

Upvotes: 3

Related Questions