【问题标题】:Access relation of pivot table in LaravelLaravel中数据透视表的访问关系
【发布时间】:2019-02-19 09:00:39
【问题描述】:

我有三个模型BillProductProcessBillProduct 具有多对多关系,并且数据透视表有一些额外的字段。我编写了Bill 模型类,如下所示:

<?php
    class Bill extends Model
    {
           function products(){
                return $this->belongsToMany(\App\Product::class)
                    ->withPivot('process_id') // the id of the Process 
                    ->withTimestamps();
            }
    }

Process 模型是一个包含idname 的简单表。我正在关联数据透视表中的 id 以引用进程,名称可能会随着时间而改变,但仍然引用相同的概念,因此我无法关联名称。

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

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

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

谢谢

【问题讨论】:

    标签: php laravel relationship


    【解决方案1】:

    如果与 Process 没有直接关系,您可能需要在您的 Product 模型上添加一个帮助器以获得 Process 的名称。

    在您的产品模型中:

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

    在你看来:

    <td>{{$product->processName($product->pivot->process_id) }}</td> 
    

    可能有更好的方法,但这个概念应该可行。

    【讨论】:

      【解决方案2】:

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

      Process::find($product->pivot->process_id)->name;
      

      我不建议这样做,因为您已经在遍历数组,因此执行此类操作的开销会非常大。

      另一种解决方案是创建一个名为 BillProductPivot 的 Pivot 类,该类将具有返回 ProductProcess 的关系,然后当您调用它们时,您应该使用预先加载来获取关系。最终产品可能如下所示:

      $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
      

      【讨论】:

        【解决方案3】:

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

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

        通过在Bill 上的products 关系中使用此模型

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

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

        <td>{{$product->pivot->process->name}}</td> 
        

        (很遗憾,我现在无法仔细检查:/)

        【讨论】:

          猜你喜欢
          • 2021-03-09
          • 2017-07-22
          • 2018-11-12
          • 2014-09-29
          • 2014-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多