我是一个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())
]);
}
}
型
我做错了什么?
2条答案
按热度按时间jm81lzqq1#
检查
Education
模型中的education_type_id
是否对应于数据库中EducationType
模型中的现有id
。可能是外键设置不正确。bvn4nwqk2#
我已经找到了解决方案!在控制器中,我首先需要检索记录:
字符串
}