php Laravel JsonResource外部表为空

xkftehaa  于 2023-11-16  发布在  PHP
关注(0)|答案(2)|浏览(145)

我是一个Laravel和Inertia的初学者,我使用Laravel 10和Inertia和React。
当我转到索引页时,字段“$this->typeEducation->title”已填充,但当我单击编辑时,该字段为空。然后我收到错误消息:“尝试读取null上的属性“title”
型号:

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())
        ]);
    }
}


我做错了什么?

jm81lzqq

jm81lzqq1#

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

bvn4nwqk

bvn4nwqk2#

我已经找到了解决方案!在控制器中,我首先需要检索记录:

class EducationController extends Controller {
public function index(): Response
{
    return Inertia::render('School/Education/EducationIndex', [
        'education' => EducationResource::collection(Education::all())
    ]);
}

public function edit(string $id): Response
{
    $education = Education::findOrFail($id);
    $education->load(['typeEducation']);
    return Inertia::render('School/Education/Edit', [
        'education' => new EducationResource($education),
        'educationTypes' => EducationTypeResource::collection(EducationType::all())
    ]);
}

字符串
}

相关问题