php - 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
未加载产品对象。我想在上面的循环中显示产品名称。
解决方案
尝试这样做:
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
to,orderLines
因为 order 有很多 orderLines。
在你的刀片中:
@foreach($order->orderLines as $orderLine)
<tr>
<td>{{$orderLine['product']->title}}</td>
<tr>
@endforeach
推荐阅读
- math - 给定两个变换(放大中心),找到比例中心(视口内)
- node.js - Express 服务器代理多个应用程序
- javascript - JQuery UI Slider中的不同值
- acumatica - 通过 Rest API 创建新潜在客户时,地址状态未更新
- visual-studio-code - 如何在 VSCode 中反向导航 Ctrl+单击文件?
- git - 有没有办法将最新的更改从开发合并到一个文件?
- r - 如何在 dplyr 和 purrr 中生成具有特定模式的多个列而不是使用循环?
- unit-testing - Azure DevOps“仅运行影响测试”不适用于 XUnit 测试?
- sql - 使用更新集添加变量
- javascript - 附加的 html 总是添加到最后一个动态创建的 div