Cannot display related entities in one-to-many rel

2019-08-29 09:14发布

问题:

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');
}

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:

#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

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));
}

回答1:

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


回答2:

replace {{ $product->product->name ?? 'no products' }} by:

{{ $product->name ?? 'no products' }}

Also edit @foreach($products as $product) to @foreach($products->products->all() as $product)