Laravel 关系错误:未定义属性:第 1 行的 Illuminate\Database\Eloquent\Collection::$id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40022929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel relationship error: Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1
提问by omrakhur
I have two models Companyand Employee, with corresponding tables in MySQL, companies, and employees.
我有两个模型Company和Employee,在 MySQL 中有相应的表companies, 和employees。
I have these Many-to-One relationships defined:
我定义了这些多对一关系:
In the Companymodel:
在Company模型中:
public function employees(){
return $this->hasMany('App\Employee','company');
}
In the Employeemodel:
在Employee模型中:
public function company(){
return $this->belongsTo('App\Company','company');
}
companyabove in the methods is an unsigned integer foreign key present in the employeestable.
company上面的方法是employees表中存在的无符号整数外键。
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->idto get the IDs of all the employees only and not the other rows, it gives me the error:
在 tinker 我已经尝试过$company->employees;,它返回所选公司中所有员工的列表。但是,当我$company->employees->id只获取所有员工的 ID 而不是其他行时,它给了我错误:
PHP error: Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1
采纳答案by Neat
Well $company->employeesreturns a collection, ->idis not a property in the collection, thats why you get the error.
那么$company->employees返回一个集合,->id它不是集合中的一个属性,这就是你得到错误的原因。
If you want to retrieve an array containing all the id's of your employees you might do this:
如果您想检索一个包含所有员工 ID 的数组,您可以这样做:
$company->employees()->lists('id');
If you're reading this and using laravel ^5.3.*then the answer would be:
如果您正在阅读本文并使用 laravel,^5.3.*那么答案将是:
$company->employees()->pluck('id');
This would return a collection with all id's, if you want it to be an array you can chain the ->toArray()behind it.
这将返回一个包含所有 id 的集合,如果您希望它是一个数组,您可以将->toArray()其链接到后面。

