Laravel的hasMany()的关系没有得到值

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

我有三个表:客户,订单和书籍。订单存储客户ID和书籍商店订单ID。

为了客户的网页上列出的订单项,我添加此方法对客户模型:

public function customerOrders()
{
    return $this->hasMany('App\Order', 'id_customer');
}

工作正常。

现在我需要抢书每个订单。所以我添加此方法订购型号:

public function orderBooks()
{
    return $this->hasMany('App\OrderBooks', 'id_order');
}

当我试图得到一个循环内orderBooks信息:

@foreach($customer->customerOrders as $order)
...
{{ $order->orderBooks->id }}
...

Laravel回报

地产[ID]不会对这种集合实例存在。

如何我将数据发送到视图:

return view('register.customers.show', compact('customer'));

迁移:

Schema::create('customers', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
});

Schema::create('orders', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('id_customer')->nullable();
    $table->foreign('id_customer')->references('id')->on('customers')->onDelete('set null');
    $table->timestamps();
});

Schema::create('books', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('id_order')->nullable();
    $table->foreign('id_order')->references('id')->on('orders')->onDelete('set null');
    $table->timestamps();
});
php laravel laravel-5.7
2个回答
2
投票

尝试这个:

@foreach($customer->customerOrders as $order)
    @foreach($order->orderBooks as $book)
        {{ $book->id }}
    @endif
@endif

0
投票

此错误:

地产[ID]不会对这种集合实例存在。

正在发生的事情,因为你想从集合获得id,你想从集合里面的对象id

试试这个:


@foreach($customer->customerOrders->orderBooks as $book)
{{ $book->id }}
@endforeach

© www.soinside.com 2019 - 2024. All rights reserved.