如何在laravel 5.6中通过循环检索实例集合

时间:2018-06-17 12:12:58

标签: php laravel

我想知道如何在一组实例中获取对象的属性 注意:这个集合是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可以检索但我无法获得视图中的产品项目

2 个答案:

答案 0 :(得分:1)

因为您有一对一的关系,所以您应该使用 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

答案 1 :(得分:0)

产品是一个对象数组。但请看一下 Amandeep Singh 回答

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