dpw50696 2018-06-17 10:28
浏览 8

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

I have an invoice model that should have 1 user and many products here I set the user relation and I retrieve it in view fine but I cant go 1 level deeper and get the items of products relation take a look at my code

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

and here is my controller

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

and here is the view

<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

now the problem here is I can see the costumer well but i cant access the products relation ship here is a dd of $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 [▶]

all i understand is that hasmany is a collection of items returning but i dont uderstand how to access them and show them .

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?