我有三个模型Bill
,Product
和Process
。Bill
与ManyToMany关系Product
并且数据透视表有一些额外的字段。我编写如下的Bill
模型类:
<?php
class Bill extends Model
{
function products(){
return $this->belongsToMany(\App\Product::class)
->withPivot('process_id') // the id of the Process
->withTimestamps();
}
}
该Process
模型是带有id
和的简单表name
。我正在关联数据透视表中的ID以引用流程,该名称可能会随时间变化,但仍引用相同的概念,因此我无法关联该名称。
单个Bill
商品的显示页面列出了表中关联的产品,如下所示:
@foreach($bill->products as $product)
<tr>
<td>{{$product->barcode}}</td>
<td>{{$product->pivot->process_id}}</td>
</tr>
@endforeach
所以问题是我需要进程的名称,但是我有ID。我不确定如何获得这个名字。
谢谢
我认为您可以使用自己的数据透视模型,例如ProductBill
以实现此目的。
class ProductBill extends Pivot {
public function process() {
return $this->belongsTo(Process::class);
}
}
通过在您的关系中使用此模型products
Bill
class Bill extends Model {
function products() {
return $this->belongsToMany(\App\Product::class)
->withPivot('process_id')
->using(ProductBill::class)
->withTimestamps();
}
}
访问时,$product->pivot
您应该获得MyCustomPivotModel
now的实例,因此您应该能够执行以下操作:
<td>{{$product->pivot->process->name}}</td>
(不幸的是,我现在无法再次检查:/)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句