使用php artisan tinker
,我可以提取与该示例有关的数据库中的第一个用户的产品表
>>> App\User::first()->product;
=> Illuminate\Database\Eloquent\Collection {#2912
all: [
App\product {#2898
id: 2,
owner_id: 2,
title: "ListingTestTitle",
description: "ListingTestDescription",
price: "420.69",
created_at: "2019-11-08 13:21:28",
updated_at: "2019-11-08 13:21:28",
},
],
}
但是,当我尝试进一步进入此收藏集并只是抓住标题时,出现以下错误
>>> App\User::first()->product->title;
Exception with message 'Property [title] does not exist on this collection instance.'
无论我尝试拉哪个属性,我都会遇到相同的问题。
因为product
是您的hasMany
模型中的User
关系,所以也从关系集合中访问第一个关系
App\User::first()->product->first()->title;
或者只是将关系更改为hasOne
希望这会有所帮助
App\User::first()->product->first()->title;
您可以在hasOne
模型中使用User
关系
App\User::first()->product->first()->title;