【发布时间】:2019-08-24 20:09:47
【问题描述】:
我有一个包含以下表格和关系的数据库: 发票、订单和产品 每个因素都有几个订单,每个订单都指向一个产品。
发票型号:
class Invoice extends Model
{
public function orders()
{
return $this->hasMany(Order::class);
}
}
订购型号:
class order extends Model
{
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
public function product()
{
return $this->belongsTo('App\Product');
}
}
产品型号:
class product extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class);
}
}
每个订单的名称是产品ID的外键,
$table->unsignedBigInteger('name')->references('id')->on('products')->default(0);
在我的模板中,我可以显示带有如下订单的发票:
{{$invoice->title}}
{{$invoice->client_address}}
@foreach($invoice->orders as $order)
{{$order->name}}
${{$order->price}}
{{$order->qty}}
${{$order->qty * $order->price}}
@endforeach
使用此功能:
public function show($id)
{
$invoice = Invoice::with('orders')->findOrFail($id);
return view('admin.invoice.show.main', compact('invoice'));
}
如何在订单记录中显示产品名称:
{{$order->product->name}}
我在单个循环中使用 before(例如,产品和类别) 但在这个例子中,我们有 3 个关系,并且之前使用了一个紧凑的方法。
我的产品表是:
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('desc');
$table->string('price');
$table->string('image');
$table->string('count');
$table->string('status');
$table->unsignedBigInteger('category_id')->default(0);
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
【问题讨论】:
-
似乎是什么问题?
标签: laravel laravel-5 eloquent