首页 > 解决方案 > Laravel:在多个级别上加载对象

问题描述

我有以下表格:

订单:id等...

order_lines : id、order_id、product_id 等...

产品:ID,名称等...

定义了外键。

我的 Laravel 模型定义为:

class Order

 public function orderLine()
    {
        return $this->hasMany('App\OrderLine');
    }
class OrderLine

public function order()
    {
        return $this->belongsTo('App\Order');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }
class Product

public function orderLine()
    {
        return $this->hasMany('App\OrderLine');
    }

我已经尝试了很多东西,但没有任何效果。这是对我来说最好的解决方案,但它不起作用。

class OrderController

public function show($id)
    {
        $user = Auth::user();
        $order = Order::where('user_id', '=', $user->id)->with(['orderLine.product'])->findOrFail($id);
        return view('layouts/order/index', compact('order'));
    }

我很难在视图中显示以下数据:

@foreach($order->orderLine as $key => $orderLine)
<tr>
    <td>{{$orderLine->product->name}}</td>
<tr>
@endforeach

未加载产品对象。我想在上面的循环中显示产品名称。

标签: phplaravel

解决方案


尝试这样做:

public function show($id)
    {
        $user = Auth::user();
        $order = Order::with(['orderLines', 'orderLines.product'])
                      ->where('user_id', '=', $user->id)
                      ->findOrFail($id);
        return view('layouts/order/index', compact('order'));
    }
class OrderLine

public function order()
    {
        return $this->belongsTo(\App\Order::class, 'order_id');
    }

    public function product()
    {
        return $this->belongsTo(\App\Product::class, 'product_id');
    }
class Order

 public function orderLines()
    {
        return $this->hasMany(\App\OrderLine::class);
    }

将名称更改为orderLineto,orderLines因为 order 有很多 orderLines。

在你的刀片中:

@foreach($order->orderLines as $orderLine)
<tr>
    <td>{{$orderLine['product']->title}}</td> 
<tr>
@endforeach

推荐阅读