我的代码中有一对多的关系,我想在我的视图中显示,但是我收到NULL
错误。以下是具有已定义关系的模型。
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));
这是我的观点,但它始终显示 no products :
@foreach ($products as $product)
<td>{{ $product->product->name ?? 'no products' }}</td>
@endforeach
当我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"
修改
这是我的完全控制器,我得到了与用户的关系,没有问题,这是一个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));
}
答案 0 :(得分:1)
将{{ $product->product->name ?? 'no products' }}
替换为:
{{ $product->name ?? 'no products' }}
同时将@foreach($products as $product)
修改为@foreach($products->products->all() as $product)
答案 1 :(得分:1)
您现在已经包含了控制器代码。所以实际上不是
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));
}
并在您看来显示您可以使用的发票产品:
@forelse ($invoice->products as $product)
{{ $product->name }}
@empty
no products
@endforelse