Reputation: 11
I have a many-to-many relationship between Part and Material models. It's working perfectly with a pivot table.
Now I just added another column to the pivot table called 'provider_id'. What I need is when a User adds a Material to a Part he also selects which provider for that Material (because Material-Provider is also a many-to-many relationship), so when I do:
@foreach($parts as $key => $value)
@foreach($value->materials as $mkey => $mvalue)
{{ $mvalue->provider_id }}
@endforeach
@endforeach
I get the provider ID, thats ok. But I want to get it's name instead. Something like $mvalue->provider->name. How can I do it?
Here are my pivot table migration:
Schema::create('material_part', function (Blueprint $table) {
$table->integer('part_id')->unsigned();
$table->foreign('part_id')->references('id')
->on('parts')->onDelete('cascade');
$table->integer('material_id')->unsigned();
$table->foreign('material_id')->references('id')
->on('materials')->onDelete('cascade');
$table->integer('provider_id')->unsigned();
$table->foreign('provider_id')->references('id')
->on('providers')->onDelete('cascade');
$table->timestamps();
});
Part Model:
class Part extends Model
{
public function materiales(){
return $this->belongsToMany('App\Material', 'material_part')->withPivot('part_id', 'provider_id');
}
}
I also have the same relationship in Material model.
Provider Model:
public function materials(){
return $this->belongsToMany('App\Material', 'material_provider');
}
Every relation is working fine but accesing single Provider of each Material of each Part.
Thanks!
EDIT:
I'm trying with this (with no success yet)
public function materials(){
return $this->belongsToMany('App\Material', 'material_part')
->withPivot('part_id', 'provider_id')
->join('providers', 'material_part.provider_id', '=', 'providers.id');
//SELECT * FROM `material_parte` INNER JOIN providers ON material_part.provider_id = providers.id
}
Upvotes: 0
Views: 1323
Reputation: 11
I just got it:
public function materiales(){
return $this->belongsToMany('App\Material', 'material_part')
->withPivot('part_id', 'provider_id')
->join('providers', 'material_part.provider_id', '=', 'providers.id')
->select('providers.name as pivot_providers_name', 'materials.*');
//SELECT * FROM `material_part` INNER JOIN providers ON material_part.provider_id = providers.id
}
THANKS!
Upvotes: 0
Reputation: 15941
for getting values from pivot
table you use pivot->propertyName
@foreach($parts as $key => $value)
@foreach($value->materials as $mvalue)
{{ $mvalue->pivot-> provider_id }}
@endforeach
@endforeach
Hope this helps
Upvotes: 1