无法从产品表中指定'title'-php artisan tinker

问题描述 投票:0回答:2

使用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.'

无论我尝试拉哪个属性,我都会遇到相同的问题。

php laravel eloquent artisan tinker
2个回答
0
投票

因为product是您的hasMany模型中的User关系,所以也从关系集合中访问第一个关系

App\User::first()->product->first()->title;

或者只是将关系更改为hasOne

希望这会有所帮助


0
投票
App\User::first()->product->first()->title;

0
投票

您可以在hasOne模型中使用User关系

App\User::first()->product->first()->title;
© www.soinside.com 2019 - 2024. All rights reserved.