dousa1630 2016-08-04 07:48
浏览 27

Laravel雄辩的关系

This is my problem.

I have a model called Product that defines a relation like this

Product.php

public function maintenanceById($maintenanceId){
        return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code']);
    }

I use this method in a view like so

    @foreach($maintenance as $value)

        @if($product->maintenanceById($value->id)->getResults())
          <th>
           {{$product->maintenanceById($value->id)->getResults()[0]->pivot->price}}
          </th>
       @else
          <th></th>
       @endif

   @endforeach

getResults returns an array that has a single object in it so I have to access the object within using getResults()[0]. Is there a way to make the returned value into an object so I can simply do this:

$product->maintenanceById($value->id)->getResults()->pivot->price

EDIT: Ive tried this and it works

public function maintenanceById($maintenanceId){
    return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->get();
}

Then in the view

@foreach($maintenance as $value)
   @if(!$product->maintenanceById($value->id)->isEmpty())
      <th>£ {{$product->maintenanceById($value->id)->first()->pivot->price}}</th>
  @else
      <th></th>
  @endif
@endforeach

But when I try the following code it doesn't work.

public function maintenanceById($maintenanceId){
    return $this->belongsToMany(Maintenance::class, 'product_maintenance')->where('maintenance_id', '=', $maintenanceId)->withPivot(['price', 'code'])->first();
}


@foreach($maintenance as $value)
   @if(!$product->maintenanceById($value->id)->isEmpty())
        <th>£ {{$product->maintenanceById($value->id)->pivot->price}}</th>

       @else
           <th></th>
       @endif
   @endforeach
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 r包runway详细安装教程
    • ¥15 Html中读取Json文件中数据并制作表格
    • ¥15 谁有RH342练习环境
    • ¥15 STM32F407 DMA中断问题
    • ¥15 uniapp连接阿里云无法发布消息和订阅
    • ¥25 麦当劳点餐系统代码纠错
    • ¥15 轮班监督委员会问题。
    • ¥20 关于变压器的具体案例分析
    • ¥15 生成的QRCode圖片加上下載按鈕
    • ¥15 板材切割优化算法,数学建模,python,lingo