Alejandro Beltran
Alejandro Beltran

Reputation: 327

Laravel 5 relationship of three models

Orders Table

 id   total        created_at
 ---+------------+--------------
 2    1500.99      2017-02-02

Items Table

 id   order_id    product_id   quant
 ---+-----------+------------+-------
 66    2              5          1
 67    2              6          2
 68    3              5          2

Products Table

 id   name        created_at
 ---+------------+--------------
 5   PC Intel    2017-02-02
 6   PC AMD      2017-02-02

Models

//Order Model
class Order extends Model{
 public function items(){
    return $this->hasMany('App\Item');
 }
}

// Item Model
class Item extends Model{
 public function producto(){
    return $this->hasOne('App\Product');
}
} 

// Product Model
class Product extends Model{
 public function item(){
    return $this->hasOne('App\Item');
 }
}

I want display Product name of relationhip models. For example I have

 $order = Order::with('items')->find($id);

But How I can add third Model for print name of product?? For example for print this

$order->items->product->name //"PC Intel"

Upvotes: 1

Views: 41

Answers (2)

dparoli
dparoli

Reputation: 9161

Given your tables, Item should be like this:

// Item Model
class Item extends Model{
    public function product(){
        return $this->belongsTo('App\Product');
    }

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

For retrievenig product name you shoud know that items() return a collection so:

$order->items[0]->product->name //"PC Intel"

Upvotes: 0

EddyTheDove
EddyTheDove

Reputation: 13259

$order->items returns a collection. You cannot access properties.

Instead, you have to loop through all objects in the collection

foreach($order->items as $item) {
    $item->product->name;
}

Perhaps you should add products to your eager loading

order = Order::with('items.producto')->find($id);

Upvotes: 1

Related Questions