在laravel 6应用程序中,我有一个资源收集,它对我来说很好:
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,但是使用了行:
'user_id' => $this->whenLoaded('user_id'),
我有错误:
"message": "Method Illuminate\\Support\\Collection::relationLoaded does not exist.",
哪条路是有效的?
修改后的 : --我在模型中添加了关系并制作了:
'user' => $userSkill->whenLoaded('user'),
或
'user' => $this->whenLoaded('user'),
我有错误:
Call to undefined method App\UserSkill::whenLoaded(
我猜想这个错误是我从Collection中调用的。有多正确?
谢谢!
发布于 2020-03-11 03:35:51
relationLoaded()
是从Illuminate\Database\Eloquent\Model
上的HasRelationships
特性继承而来的方法。
您的代码试图在Illuminate\Support\Collection
的一个实例上访问它。
尝试访问关系user
而不是关键user_id
。就像这样:
$this->whenLoaded('user')
https://stackoverflow.com/questions/60631583
复制