Laravel JsonResource 外部表为空

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

我是 Laravel 和惯性的初学者。 我使用带有 Inertia 的 Laravel 10 并做出反应。

当我进入索引页面时,“$this->typeEducation->title”字段已被填充,但是当我单击编辑时,该字段为空。然后我收到错误消息:“尝试读取 null 上的属性“标题”

型号:

class Education extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'education_type_id',
        'is_active',
        'start_date',
        'end_date',
    ];

    public function typeEducation() {
        return $this->belongsTo(EducationType::class, 'education_type_id', 'id');
    }
}

资源:

class EducationResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'type' => $this->typeEducation->title,
            'isActive' => $this->is_active,
            'startDate' => $this->start_date,
            'endDate' => $this->end_date,
            'educationTypes' => EducationTypeResource::collection($this->whenLoaded('educationTypes'))
        ];
    }
}

控制器

class EducationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        return Inertia::render('School/Education/EducationIndex', [
            'education' => EducationResource::collection(Education::all())
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Education $education): Response
    {
        $education->load(['typeEducation']);
        return Inertia::render('School/Education/Edit', [
            'education' => new EducationResource($education),
            'educationTypes' => EducationTypeResource::collection(EducationType::all())
        ]);
    }
}

我做错了什么?

php laravel laravel-10 laravel-middleware laravel-eloquent-resource
1个回答
0
投票

检查

education_type_id
模型中的
Education
是否与数据库中
id
模型中现有的
EducationType
相对应。可能是外键设置不正确。

© www.soinside.com 2019 - 2024. All rights reserved.