【发布时间】:2020-03-05 03:48:57
【问题描述】:
使用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是一个单数名词,应该反映一个实例,所以让它以Collection的形式返回hasMany()是错误的。如果要使用hasMany()并获取多个Product实例,则此关系应为products,如果要使用hasOne()或belongsTo()并获取单个Product实例,则应为product。另外,类名是StudlyCase,所以是App\Product,而不是App\product。 -
我将致力于更好的命名约定。非常感谢您的信息
标签: php laravel eloquent laravel-artisan tinker