1
的Poperty我有一个人物表Laravel模型非对象
CREATE TABLE `people` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`job_title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`profile_pic` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`departments` varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
的一个部门表
CREATE TABLE `departments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`people_id` int(11) NOT NULL,
`department_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
- 一个人可以在许多部门
- 在部门表foreign_key是people_id
个在我的人模型
public function departments()
{
return $this->hasMany('App\Models\Departments', 'id', 'people_id');
}
,最后我尝试和返回一些结果
return $people::find(1)->departments;
我得到的错误,
**ErrorException in web.php line 129:
Trying to get property of non-object**
原谅我,如果这是一个愚蠢的错误,我有使用laravel一段时间,但从来没有建立与之前的关系模型。
你确定你的模型类叫做Departaments?通常它是单数。所以它会是:'$ this-> hasMany('App \ Models \ Department')'; – Troyer
不,是部门 – LeBlaireau
尝试:'返回$ this-> hasMany('App \ Models \ Departments','people_id','id');' – Troyer