I have three models Bill
, Product
and Process
. Bill
has a ManyToMany relationship with Product
and the pivot table have some extra fields. I write the Bill
model class like follow:
<?php
class Bill extends Model
{
function products(){
return $this->belongsToMany(\App\Product::class)
->withPivot('process_id') // the id of the Process
->withTimestamps();
}
}
The Process
model is a simple table with an id
and a name
. I am associating the id in the pivot table for reference the Process, the name could change over time but still referring the same concept so I can't associate the name.
The show page for a single Bill
lists the products associated in a table like follow:
@foreach($bill->products as $product)
<tr>
<td>{{$product->barcode}}</td>
<td>{{$product->pivot->process_id}}</td>
</tr>
@endforeach
So the problem is that I need the name of the process, but I have the id. I'm not sure how I could get the name.
Thanks
Follow these steps, to find the data source of a pivot table: Select any cell in the pivot table. On the Ribbon, under the PivotTable Tools tab, click the Analyze tab (in Excel 2010, click the Options tab). In the Data group, click the top section of the Change Data Source command.
On the relationships for both User and Target , tack on a ->withPivot('type') which will instruct Laravel to include that column. Then once you have your result set, you can access the field with $user->pivot->type .
The pivot table in laravel is a structured value that is grouped and aggregated in the individual items where the extensive table is obtained or accessed in the form of a spreadsheet, database, or other discrete functions.
I think you can use an own Pivot Model, e.g. ProductBill
in order to achieve this.
class ProductBill extends Pivot {
public function process() {
return $this->belongsTo(Process::class);
}
}
By using this model in your products
relation on Bill
class Bill extends Model {
function products() {
return $this->belongsToMany(\App\Product::class)
->withPivot('process_id')
->using(ProductBill::class)
->withTimestamps();
}
}
When accessing $product->pivot
you should get an instance of ProductBill
now, hence you should be able to do the following:
<td>{{$product->pivot->process->name}}</td>
(Unfortunatelly I not able to doublecheck right now :/)
Without having a direct relation to Process
you will likely need to add a helper on your Product
model to get the name of Process
.
In your Product model:
public function processName($processId) {
return Process::where('id', $processId)->pluck('name')->first();
}
In your view:
<td>{{$product->processName($product->pivot->process_id) }}</td>
There may be a better way, but concept this should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With