2017-05-09 45 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不存在。