我有一张人员表
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;
在我的人物模型中
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一段时间,但从未在之前设置过具有关系的模型。
答案 0 :(得分:0)
试试这段代码: -
Get All records
$people = People::with('departments')->get();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
Get 1 record
$people = People::with('departments')->first();
$people = json_decode(json_encode($people),true) //Convert in to array
echo "<pre>"; print_r($people); die; //print it
希望它有所帮助!
答案 1 :(得分:0)
所以最后这是一个愚蠢的问题。
$people::find(1)->departments;
Find需要一个id,但id不存在。