cyber-leech
cyber-leech

Reputation: 37

Laravel Relationship between Three Models

sold_items:
id    order_id   customer_id   name      
--    --------   -----------   ----
1     5          14            An object

orders:
id      po_num
--      ------
...     ...
5       123


customers:
id      name
--      ----
...     ...
14      John Doe

A SoldItem has an order_id and a customer_id.

I'm trying to define a hasOne relationship between an Order and its Customer through the SoldItem without having to insert a customer_id column in the Order model's table.

hasOneThrough seemed to be the solution but I couldn't figure out where to go from there, or is that even the answer?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];

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

    public function customer()
    {
        // return $this->hasOneThrough();
    }
}

Upvotes: 0

Views: 85

Answers (2)

idirsun
idirsun

Reputation: 604

for Customer model

{

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


}

for Order model

{

    public function sold_items()
    {
        return $this->hasOne('App\SoldItem');
    }


}

for SoldItem model

{

    public function customer()
    {
        return $this->belongsto('App\Cutomer');
    }

     public function order()
    {
        return $this->belongsto('App\Order');
    }

}

I prefer working on their relationship first then and use with() function to get their values.

use App\Customer;

$customer = Customer::with('sold_items','sold_items.order')->get();

Upvotes: 1

cyber-leech
cyber-leech

Reputation: 37

I ended up making the Customer an attribute of the Order through its sold_items with:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $guarded = ['id'];

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

    public function getCustomerAttribute()
    {
        return $this->sold_items->first()->customer;
    }
}

Upvotes: 0

Related Questions