Laravel 中数据透视表的访问关系

Gio*_*gio 5 php relationship laravel

我有三个模型BillProductProcessBill有一个 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();
            }
    }
Run Code Online (Sandbox Code Playgroud)

Process模型是一个带有id和 的简单表格name。我正在关联数据透视表中的 id 以参考流程,名称可能会随着时间的推移而改变,但仍然引用相同的概念,因此我无法关联名称。

单个的显示页面Bill列出了在表格中关联的产品,如下所示:

@foreach($bill->products as $product)
     <tr>
        <td>{{$product->barcode}}</td>
        <td>{{$product->pivot->process_id}}</td> 
     </tr>
@endforeach
Run Code Online (Sandbox Code Playgroud)

所以问题是我需要进程的名称,但我有 id。我不知道我怎么能得到这个名字。

谢谢

Tsc*_*sch 4

我认为您可以使用自己的枢轴模型,例如ProductBill为了实现这一目标。

class ProductBill extends Pivot {

    public function process() {
        return $this->belongsTo(Process::class);
    }

}
Run Code Online (Sandbox Code Playgroud)

通过在您的关系中使用此模型productsBill

class Bill extends Model {

    function products() {
        return $this->belongsToMany(\App\Product::class)
            ->withPivot('process_id')
            ->using(ProductBill::class)
            ->withTimestamps();
    }

}
Run Code Online (Sandbox Code Playgroud)

访问时$product->pivot您应该获得 now 的实例ProductBill,因此您应该能够执行以下操作:

<td>{{$product->pivot->process->name}}</td> 
Run Code Online (Sandbox Code Playgroud)

(不幸的是我现在无法仔细检查:/)