使用加载到资源集合时出现错误

问题描述 投票:0回答:1

在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时使用,但使用line:

'user_id' => $this->whenLoaded('user_id'),

我出错了:

"message": "Method Illuminate\\Support\\Collection::relationLoaded does not exist.",

哪种方法有效?

MODIFIED:我在模型和制作中添加了关系:

  'user' => $userSkill->whenLoaded('user'),

  'user' => $this->whenLoaded('user'),

我出错了:

Call to undefined method App\UserSkill::whenLoaded(

我想这是我从Collection调用的错误。如何正确?

谢谢!

laravel resources
1个回答
1
投票

[relationLoaded()是从HasRelationshipsIlluminate\Database\Eloquent\Model特性继承的方法。

您的代码正在尝试在Illuminate\Support\Collection的实例上访问它。

尝试访问关系user,而不是键user_id。像这样:

$this->whenLoaded('user')
© www.soinside.com 2019 - 2024. All rights reserved.