php - 如何通过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 并且可以检索,但我无法查看产品项目
解决方案
因为您有一对一的关系,所以您应该使用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
推荐阅读
- ruby-on-rails - 减少对 RSpec 控制器规范的网络请求,如何设置标头
- c# - Web API 帖子正文属性 null
- c# - 在 c# [UWP] 中从 '\ud835' 格式转换为 ""
- python - 附加到 numpy 数组中的特定行
- java - 用于 DataMatrix 解码的 Libdmtx 与 ZXing?
- excel - 索引匹配返回不正确的值
- php - 使用从 mysqli php 到 MySql 数据库的 http 请求在 Ionic2 TypeScript 应用程序中检索希伯来语
- angular - Angular:处理自定义事件处理程序执行结束的指令
- angular - 在Angular 2中成功提交表单时发送Httpclient POST
- php - 如何根据 PHP 中的引用赋值