Php 如何在laravel 5.6中检索2个定义的关系

Php 如何在laravel 5.6中检索2个定义的关系,php,laravel,Php,Laravel,我有一个发票模型,应该有一个用户和许多产品在这里我设置了用户关系,我在视图中检索它很好,但我不能更深一层,并获得产品关系的项目看看我的代码 public function user() { return $this->hasOne('App\Client','id','client_id'); } public function products(){ return $this->hasMany('App\Product','id','product_id'); }

我有一个发票模型,应该有一个用户和许多产品在这里我设置了用户关系,我在视图中检索它很好,但我不能更深一层,并获得产品关系的项目看看我的代码

 public function user() {
    return $this->hasOne('App\Client','id','client_id');
}
public function products(){
    return $this->hasMany('App\Product','id','product_id');
}
这是我的控制器

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

<td>{{$invoice->id}}</td>
<td>{{$invoice->title}}</td>
<td><a href="/admin/invoices/{{$invoice->id}}">{{$invoice->description}}</a></td>

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

我所了解的是hasmany是一个返回的项目集合,但我不知道如何访问和显示它们。

您需要在每个客户的内部循环您的产品集合,而且我怀疑您的映射定义show to loop我的意思是使用什么变量?我只是不明白你的意思,比如说,
@foreach($client->products as$product)@endforeach
内部
$clients
循环
  0 => Invoice {#307 ▼
  #fillable: array:4 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▶]
  #original: array:7 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:2 [▼
    "user" => Client {#310 ▶}
    "products" => Collection {#316 ▼
      #items: array:1 [▼
        0 => Product {#312 ▼
          #fillable: array:5 [▶]
          #connection: "mysql"
          #table: null
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:8 [▶]