Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel中透视表的访问关系_Php_Laravel_Relationship - Fatal编程技术网

Php Laravel中透视表的访问关系

Php Laravel中透视表的访问关系,php,laravel,relationship,Php,Laravel,Relationship,我有三种型号账单,产品和流程Bill与Product有很多关系,透视表有一些额外的字段。我编写了Bill模型类,如下所示: <?php class Bill extends Model { function products(){ return $this->belongsToMany(\App\Product::class) ->withPivot('process_

我有三种型号
账单
产品
流程
Bill
Product
有很多关系,透视表有一些额外的字段。我编写了
Bill
模型类,如下所示:

<?php
    class Bill extends Model
    {
           function products(){
                return $this->belongsToMany(\App\Product::class)
                    ->withPivot('process_id') // the id of the Process 
                    ->withTimestamps();
            }
    }
@foreach($bill->products as $product)
     <tr>
        <td>{{$product->barcode}}</td>
        <td>{{$product->pivot->process_id}}</td> 
     </tr>
@endforeach
所以问题是我需要进程的名称,但我有id。我不确定如何才能获得名称


谢谢

流程没有直接关系
您可能需要在
产品
模型上添加一个助手,以获得
流程
的名称

在您的产品模型中:

public function processName($processId) {
    return Process::where('id', $processId)->pluck('name')->first();
}
在你看来:

<td>{{$product->processName($product->pivot->process_id) }}</td> 
{{$product->processName($product->pivot->process\u id)}

也许有更好的方法,但这个概念应该有效。

我知道这不是最优雅的解决方案。但你可以简单地做:

Process::find($product->pivot->process_id)->name;
不过我不建议这样做,因为您已经在一个数组中循环,所以这样做的开销将相当大

另一个解决方案是创建一个名为say
BillProductPivot
的Pivot类,该类具有返回
Product
Process
的关系,然后在调用它们时,应该使用渴望加载来获取关系。最终产品可能如下所示:

$bill->load('productPivots', 'productPivot.process', 'productPivot.product');

@foreach($bill->productPivots as $productPivot)
 <tr>
    <td>{{$productPivot->product->barcode}}</td>
    <td>{{$productPivot->process->name}}</td> 
 </tr>
@endforeach
$bill->load('productPivots','productPivot.process','productPivot.product');
@foreach($bill->productPivot作为$productPivot)
{{$productPivot->product->barcode}
{{$productPivot->process->name}
@endforeach

我认为您可以使用自己的枢轴模型,例如
ProductBill
来实现这一点

class ProductBill extends Pivot {

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

}
通过在
账单上的
产品
关系中使用此模型

class Bill extends Model {

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

}
当访问
$product->pivot
时,您现在应该可以获得
MyCustomPivotModel
的实例,因此您应该能够执行以下操作:

<td>{{$product->pivot->process->name}}</td> 
{{$product->pivot->process->name}
(不幸的是,我现在无法再次检查:/)