无法显示一对多关系中的相关实体 [英] Cannot display related entities in one-to-many relationship

查看:60
本文介绍了无法显示一对多关系中的相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在视图中显示代码中的一对多关系,但出现NULL错误.下面是具有定义关系的模型.

I have a one-to-many relationship in my code that I want to show on my view, but I get a NULL error. Below is the model with the defined relationship.

public function products()
{
    return $this->hasMany('App\Product', 'id', 'product_id');
}

这是我的控制器方法:

$products = Invoice::with('products')->get();
return view('admin.invoices.show', 
    compact('invoice', $invoice),
    compact('clients', $clients))->with(compact('products', $products));

这是我的观点,但始终显示无产品:

This is my view, but it always displays no products:

@foreach ($products as $product)
    <td>{{ $product->product->name ?? 'no products' }}</td>
@endforeach

当我dd() $products数组时,得到以下信息:

When I dd() the $products array, I get the following:

#relations: array:1 [▼
    "products" => Collection {#321 ▼
      #items: array:1 [▼
        0 => Product {#318 ▼
          #fillable: array:5 [▶]
          #connection: "mysql"
          #table: null
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:8 [▼
            "id" => 1
            "name" => "asd"

编辑

这是我的完全控制者,我可以毫无问题地与用户建立关系,这是hasOne关系,但是我无法访问产品关系,这是主要问题

here is my full controller that i get the relation with users with no problem thats a hasOne relation but i cant access the products relation and that s main problem

public function show(Invoice $invoice)
{
    $clients = Invoice::with('user')->get();
    $products = Invoice::with('products')->get();
    return view('admin.invoices.show', compact('invoice', $invoice),compact('clients',$clients))->with(compact('products',$products));
}

推荐答案

您现在已经包含了控制器代码.所以事实上,而不是

You've included now your controller code. So in fact instead of

public function show(Invoice $invoice)
{
    $clients = Invoice::with('user')->get();
    $products = Invoice::with('products')->get();
    return view('admin.invoices.show', compact('invoice', $invoice),compact('clients',$clients))->with(compact('products',$products));
}

您只能使用:

public function show(Invoice $invoice)
{
    return view('admin.invoices.show', compact('invoice', $invoice));
}

并在视图中显示可以使用的发票产品:

and in your view to display invoice products you can use:

@forelse ($invoice->products as $product) 
  {{ $product->name }}
@empty
   no products
@endforelse

这篇关于无法显示一对多关系中的相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆