在资源集合中使用 whenLoaded 我得到了错误
Using whenLoaded in Resource Collection I got error
在 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 中调用的。
有多正确?
谢谢!
relationLoaded()
是从 Illuminate\Database\Eloquent\Model
上的 HasRelationships
特征继承的方法。
您的代码正试图在 Illuminate\Support\Collection
.
的实例上访问它
尝试访问关系 user
而不是它的键 user_id
。像这样:
$this->whenLoaded('user')
在 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 中调用的。 有多正确?
谢谢!
relationLoaded()
是从 Illuminate\Database\Eloquent\Model
上的 HasRelationships
特征继承的方法。
您的代码正试图在 Illuminate\Support\Collection
.
尝试访问关系 user
而不是它的键 user_id
。像这样:
$this->whenLoaded('user')