1 month ago

Pivot Model Relationship with another table

Posted 1 month ago by WCaaan

Table structure of types:

id, title

Table structure of options:

id, title, description

Table structure of option_type:

id, option_id, type_id

Table structure of option_type_size:

option_type_id, size_id, price

Table structure of size:

id, title, description

Database Explanation:

  • Item has many tiers
  • Tier has one type (Size, Option OR Addon)
  • type has many-to-many relationship with option
  • optionType has many-to-many relationship with size, in the pivot table the is additional field called price.

The Problem: In eloquent query I am able to fetch data until option_type, I don't know how to create relationship of option_type pivot model with size model.

Eloquent Query:

$items = Item::with(['tiers' => function ($query) {
			$query->with(['type' => function($query) {
		}])->where('id', 1)->get();
		return $items;

What I want to Achieve: I want to eager load option_type with sizes, for every optiontype row i may have size and its price.

The Problem: when i write a query like:

$query->with(['options' => function($query) {

It is basically saying that options have relationship with sizes which is not right, it should be optionType have relationship with size. how to can i get the data so that i would show me for record for each optiontype_id, size_id and price.

Type Model:

class Type extends Model
    protected $table = 'types';

    public function options()
	    return $this->belongsToMany(Option::class);

Option Model:

class Option extends Model
    public function type()
	    return $this->belongsToMany(Type::class);

OptionType Model:

use Illuminate\Database\Eloquent\Relations\Pivot;

class OptionType extends Pivot
	protected $table = 'option_type';

    public function optiontypesize()
		return $this->belongsToMany(Size::class, 'option_type_size', 'size_id', 'option_type_id');

Size Model:

class Size extends Model
	public function optiontypesize()
		return $this->belongsToMany(OptionType::class, 'option_type_size', 'size_id', 'option_type_id');

Please sign in or create an account to participate in this conversation.