[英]Cannot display related entities in one-to-many relationship
I have a one-to-many relationship in my code that I want to show on my view, but I get a NULL
error. 我想在视图中显示代码中的一对多关系,但出现NULL
错误。 Below is the model with the defined relationship. 以下是具有定义关系的模型。
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
This is my controller method: 这是我的控制器方法:
$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
When I dd()
the $products
array, I get the following: 当我dd()
$products
数组时,得到以下内容:
#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"
EDIT 编辑
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 这是我的完整控制器,我与用户的关系没有问题,这是hasOne关系,但是我无法访问产品关系,这是主要问题
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));
}
replace {{ $product->product->name ?? 'no products' }}
替换{{ $product->product->name ?? 'no products' }}
{{ $product->product->name ?? 'no products' }}
by: {{ $product->product->name ?? 'no products' }}
,作者:
{{ $product->name ?? 'no products' }}
Also edit @foreach($products as $product)
to @foreach($products->products->all() as $product)
还要将@foreach($products as $product)
编辑为@foreach($products->products->all() as $product)
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));
}
you can use only: 您只能使用:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.