Laravel 在资源集合中使用whenLoaded时出现错误
在laravel 6应用程序中,我有一个资源集合,对我来说可以:Laravel 在资源集合中使用whenLoaded时出现错误,laravel,resources,Laravel,Resources,在laravel 6应用程序中,我有一个资源集合,对我来说可以: class UserSkillCollection extends ResourceCollection { public static $wrap = 'user_skills'; public function toArray($request) { return $this->collection->transform(function($userSkill){
class UserSkillCollection extends ResourceCollection
{
public static $wrap = 'user_skills';
public function toArray($request)
{
return $this->collection->transform(function($userSkill){
return [
'id' => $userSkill->id,
'user_id' => $userSkill->user_id,
'user_name' => $userSkill->user_name,
'skill_id' => $userSkill->skill_id,
'skill_name' => $userSkill->skill_name,
'rating' => $userSkill->rating,
'created_at' => $userSkill->created_at,
];
});
}
除非定义了一些字段,比如user_name,否则我的键都是空值
为了摆脱它们,我试着使用whenLoaded,但使用了line:
'user_id' => $this->whenLoaded('user_id'),
我得到一个错误:
"message": "Method Illuminate\\Support\\Collection::relationLoaded does not exist.",
Call to undefined method App\UserSkill::whenLoaded(
哪种方式有效
已修改:
我在模型和制作中添加了关系:
'user' => $userSkill->whenLoaded('user'),
或
我得到一个错误:
"message": "Method Illuminate\\Support\\Collection::relationLoaded does not exist.",
Call to undefined method App\UserSkill::whenLoaded(
我想这是我从集合中称之为的错误。
正确程度如何
谢谢 relationLoaded()
是从illighted\Database\Eloquent\Model
上的hasrelations
特征继承的方法
您的代码正试图在illumb\Support\Collection
的实例上访问它
尝试访问关系user
,而不是它的键user\u id
。像这样:
$this->whenLoaded('user')
请看修改后的