【问题标题】:Laravel Models Poperty of non-objectLaravel 模型非对象的属性
【发布时间】:2017-10-07 18:13:00
【问题描述】:

我有一个 People 表

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 有一段时间了,但之前从未设置过有关系的模型。

【问题讨论】:

  • 你确定你的模型类叫做部门吗?一般是单数。所以它会是:$this->hasMany('App\Models\Department');
  • 不,是部门
  • 试试:return $this->hasMany('App\Models\Departments', 'people_id', 'id');

标签: laravel-5 eloquent models relationships


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    试试这段代码:-

    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
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 2016-02-12
      • 1970-01-01
      • 2015-12-23
      • 2017-07-18
      • 2018-02-21
      相关资源
      最近更新 更多