繁体   English   中英

Laravel hasMany()关系未获取值

[英]Laravel hasMany() relationship not getting values

我有三个表:客户,订单和帐簿。 订单存储客户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();
});

尝试这个:

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

这个错误:

属性[id]在此集合实例上不存在。

之所以发生,是因为您尝试从集合中获取id ,而您想要从集合中的对象中获取id

尝试以下方法:


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM