Mehdi Yaghoubi
Mehdi Yaghoubi

Reputation: 653

how to get the data from a column of related to model?

there is a Product model with a name column, Price model with product_id, size_id, min, max columns. and a Size model with a name column.

the prices have foreignId of size_id column.

product relation is :

public function prices() { 
  return $this->hasmany(Price::class) 
}

Price model with size_id, min, max columns.

I can get min and max but how I can get the size from the size_id column.

@foreach($products->prices as $product)
<p>{{ $product->min}}</p>
<p>{{ $product->max}}</p>
**how to get the size
<p>{{ $product->size->name}}</p>**
@endforeach

Upvotes: 0

Views: 49

Answers (1)

John Lobo
John Lobo

Reputation: 15319

You can use nested relationship like below

$products=Product::with(['prices.size'])->find($id);

make sure you have relationship size in price model

public function size(){
 return $this->belongsTo(Size::class)
}

Upvotes: 1

Related Questions