首页 > 解决方案 > 如何通过laravel 5.6中的循环检索实例集合

问题描述

我想知道如何在实例集合中获取对象的属性注意:这个集合在 hasmany 关系中,这里是代码

protected $fillable = ['title','description','client_id','product_id'];
public function user() {
    return $this->hasOne('App\Client','id','client_id');
}
public function products(){
    return $this->hasOne('App\Product','id','product_id');
}

控制器

 $clients = Invoice::with('user','products')->get();
    return view('admin.invoices.show', compact('invoice', $invoice),compact('clients',$clients));

看法

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

这是我的 $client 的 dd

#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 [▶]
          #original: array:8 [▶]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]

在这里,用户关系没有问题,因为它是 1 对 1 并且可以检索,但我无法查看产品项目

标签: phplaravel

解决方案


因为您有一对一的关系,所以您应该使用first()而不是get()尝试像这样更改您的查询

$clients = Invoice::with('user','products')->first();
return view('admin.invoices.show', compact('invoice', $invoice),compact('clients',$clients));

在您看来,您可以通过以下方式访问您的产品

{{ $clients->products->name }}
{{ $clients->products->description }}

更新

将您的模型代码更改为

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

在你看来

@foreach($clients->products as $product)
    {{ $product->name }}
@endforeach

推荐阅读