Laravel 多表关联查询:订单、产品和供应商信息展示
可以使用 Laravel 的关联模型来实现多表查询和在列表页显示相关字段。
首先,在 Order 模型中定义和 Product 和 Mina 模型的关联:
class Order extends Model
{
public function product()
{
return $this->belongsTo(Product::class, 'p_id');
}
public function mina()
{
return $this->product->belongsTo(Mina::class, 'm_id');
}
}
然后,在 OrderController 的 index 方法中,使用 with 方法预加载关联模型,并在列表页中显示相关字段:
public function index()
{
$orders = Order::with('product.mina')->get();
return view('orders.index', compact('orders'));
}
最后,在 orders.index 视图中,可以像访问 Order 模型字段一样访问 Product 和 Mina 模型的字段:
@foreach ($orders as $order)
<tr>
<td>{{ $order->id }}</td>
<td>{{ $order->product->p_name }}</td>
<td>{{ $order->product->mina->m_name }}</td>
<!-- 其他字段 -->
</tr>
@endforeach
原文地址: https://www.cveoy.top/t/topic/mlN6 著作权归作者所有。请勿转载和采集!