第1行上的Illuminate

第1行上的Illuminate

本文介绍了Laravel关系错误:未定义的属性:第1行上的Illuminate \ Database \ Eloquent \ Collection :: $ id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型CompanyEmployee,在MySQL,companiesemployees中有相应的表.

I have two models Company and Employee, with corresponding tables in MySQL, companies, and employees.

我定义了以下多对一关系:

I have these Many-to-One relationships defined:

Company模型中:

 public function employees(){
        return $this->hasMany('App\Employee','company');
    }

Employee模型中:

public function company(){
        return $this->belongsTo('App\Company','company');
    }

方法中的上述

companyemployees表中存在的无符号整数外键.

company above in the methods is an unsigned integer foreign key present in the employees table.

在修补匠中,我尝试过$company->employees;,它返回所选公司中所有员工的列表.但是,当我执行$company->employees->id仅获取所有雇员的ID而不是其他行的ID时,它给了我错误:

In tinker I have tried $company->employees;, which returns a list of all the employees in the selected company. However, when I do $company->employees->id to get the IDs of all the employees only and not the other rows, it gives me the error:

PHP error:  Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1

推荐答案

好吧$company->employees返回一个集合,->id不是该集合中的属性,这就是为什么会出现错误.

Well $company->employees returns a collection, ->id is not a property in the collection, thats why you get the error.

如果您要检索包含员工所有ID的数组,则可以执行以下操作:

If you want to retrieve an array containing all the id's of your employees you might do this:

$company->employees()->lists('id');

如果您正在阅读本文并使用laravel ^5.3.*,则答案将是:

If you're reading this and using laravel ^5.3.* then the answer would be:

$company->employees()->pluck('id');

这将返回具有所有ID的集合,如果您希望将其作为数组,则可以将->toArray()链接在其后面.

This would return a collection with all id's, if you want it to be an array you can chain the ->toArray() behind it.

这篇关于Laravel关系错误:未定义的属性:第1行上的Illuminate \ Database \ Eloquent \ Collection :: $ id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:04