使用Eloquent检索关系关系

问题描述 投票:0回答:2

我有一个包含以下表格和关系的数据库:发票,订单和产品,每个因素都有几个订单,每个订单都指向一个产品。


发票模型:

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}}

我在之前使用单循环(例如,产品和类别),但是在这个例子中我们有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
2个回答
0
投票

试试这个

$invoice = Invoice::with('orders.product')->findOrFail($id);

您可以使用类似的东西访问

@foreach($invoice->orders as $order)
..
 {{ $order->product->name }}
..
@endforeach

0
投票

我认为你的关系是错误的...每个产品都可以在几个订单内。所以:

产品型号:


class product extends Model
{
    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }
}

订单型号:

class order extends Model
{
    public function product()
    {
        return $this->hasOne('App\Product');
    }   
}

对?

然后访问:

$invoices = Invoice::with('orders.product')->get();
© www.soinside.com 2019 - 2024. All rights reserved.