Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SigalZ's avatar

Pivot table with multiple relationships

I have 3 tables:

beans, blends, roast_types

I have pivot table: bean_blend with fields:

bean_id, blend_id, roast_type_id, percent

In my models:

Bean:

 public function blends()
{
        return $this->belongsToMany(Blend::class)->withPivot('roast_type_id', 'percent');
}

//Relationship on the beans table not the pivot table. It is the default roast_type for the bean, but the bean can have different roast types on other tables, for example, the bean_blend table. We can create a blend with a bean with a different roast type than the one in the beans table.
public function roastType()
{
        return $this->belongsTo(RoastType::class);
}

Blend:

public function beans()
{
        return $this->belongsToMany(Bean::class)->withPivot('roast_type_id', 'percent');
}

RoastType:


    public function beans()
    {
        return $this->hasMany(Bean::class);
    }

Is there a way to connect the roast_type_id from the pivot table (bean_blend) to the roast_types_table?

If so, how do I do that?

0 likes
7 replies
MohamedTammam's avatar
public function roastTypes()
{
	return $this->belongsToMany(RoastType::class, 'bean_blend', 'bean_id', 'roast_type_id ');
}
SigalZ's avatar

@MohamedTammam But there is no model for it, it's a pivot table, that's the problem.

When I display records from the pivot table, I need to display the roast_type name but there is no model for the pivot table, so there is no where for me to put this function.

rajeshtva's avatar
Level 4

you can convert your pivot table into intermediate table

https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models

you can do someting like..

public function blends()
{
		return $this->belongsToMany(Blend::class)->using(BeanBlend::class);
}

public function bean()
{
		return $this->belongsToMany(Bean::class)->using(BeanBlend::class);
}

then in bean blend class , you can define something like..

use Illuminate\Database\Eloquent\Relations\Pivot;
 
class BeanBlend extends Pivot
{
		public function roastType()
{
        return $this->belongsTo(RoastType::class);
}
}
1 like

Please or to participate in this conversation.