我有以下表格:
订单 : id, etc...
order_lines : id, order_id, product_id, etc...
产品 : id, name, etc...
外键已定义。
我的 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'));
}
我很难在 View 中显示以下数据:
@foreach($order->orderLine as $key => $orderLine)
<tr>
<td>{{$orderLine->product->name}}</td>
<tr>
@endforeach
未加载产品对象。我想在上面的循环中显示产品名称。
最佳答案
尝试这样做:
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);
}
将 orderLine
的名称更改为 orderLines
,因为订单有很多 orderLines。
在你的 Blade 中:
@foreach($order->orderLines as $orderLine)
<tr>
<td>{{$orderLine['product']->title}}</td>
<tr>
@endforeach
关于php - 拉维尔 : load objects on many level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56755983/