首页 > 解决方案 > 无法从产品表中指定“标题” - php artisan tinker

问题描述

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

无论我尝试提取哪个属性,我都会遇到同样的问题。

标签: phplaraveleloquentlaravel-artisantinker

解决方案


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

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

推荐阅读