public function roastTypes()
{
return $this->belongsToMany(RoastType::class, 'bean_blend', 'bean_id', 'roast_type_id ');
}
Mar 15, 2022
7
Level 5
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?
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.