2017-05-09 54 views
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一段时间,但从来没有建立与之前的关系模型。

+0

你确定你的模型类叫做Departaments?通常它是单数。所以它会是:'$ this-> hasMany('App \ Models \ Department')'; – Troyer

+0

不,是部门 – LeBlaireau

+1

尝试:'返回$ this-> hasMany('App \ Models \ Departments','people_id','id');' – Troyer

回答

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 

希望它能帮助!

0

所以最后这是一个愚蠢的问题。

$people::find(1)->departments; 

查找需要一个id,但1的id不存在。