我正在使用 Nova 4 开发一个 Laravel 项目,并且我正在努力使用 Nova 的管理界面通过一步创建一个具有“讲师”角色的用户及其关联的 InstructorProfile。至关重要的是,两条记录必须同时创建,而不是分步创建。
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->string('surname');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->enum('role', ['admin', 'instructor', 'normal'])->default('normal');
$table->index('email');
$table->index('role');
$table->rememberToken();
$table->timestamps();
});
Schema::create('instructor_profiles', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('phoneNumber')->nullable();
$table->text('bio')->nullable();
$table->text('qualifications')->nullable();
$table->string('photo')->nullable();
$table->timestamps();
});
我尝试重写 Nova 资源中的
fill()
方法:
class InstructorProfile extends Resource
{
public static $model = \App\Models\User::class;
public static $title = 'firstName';
public static $search = [
'id', 'user.firstName', 'user.surname', 'user.email',
];
public static function indexQuery(NovaRequest $request, $query)
{
return $query->where('role', 'instructor');
}
public static $with = ['instructorProfile'];
public function fields(NovaRequest $request)
{
return [
ID::make()->sortable(),
Text::make('First Name', 'firstName')
->sortable()
->rules('required', 'max:255'),
Text::make('Surname')
->sortable()
->rules('required', 'max:255'),
Email::make('Email')
->sortable()
->rules('required', 'email', 'max:254')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Password::make('Password')
->onlyOnForms()
->creationRules('required', 'string', 'min:8')
->updateRules('nullable', 'string', 'min:8'),
Hidden::make('Role')
->default('instructor'),
Text::make('Phone Number',"instructor.phoneNumber") ,
Textarea::make('Bio',"instructor.bio")
->nullable()
->hideFromIndex(),
Textarea::make('Qualifications',"instructor.qualifications")
->nullable()
->hideFromIndex(),
Image::make('Photo',"instructor.photo")
->disk('public')
->path('instructor-photos')
->prunable()
->deletable(),
];
}
public static function fill(NovaRequest $request, $model)
{
$model = parent::fill($request, $model);
$model->instructorProfile()->create([
'created_by' => auth()->id(),
'bio' => $request->instructor_bio,
'phoneNumber' => $request->instructor_phoneNumber,
'qualifications' => $request->instructor_qualifications
]);
return $model;
}
但是,这不起作用,因为在这种情况下 $model 看起来甚至不是 User,它只是一个数组。
使用 Nova 的管理界面时,如何修改 Nova 资源以在单个操作中创建用户和 InstructorProfile 记录?
我需要一种在 Nova 中同时创建两条记录的方法,而不是分两步或两个资源。
尝试使用 HasOne 字段,这应该允许您在创建讲师时创建讲师资料
use Laravel\Nova\Fields\HasOne;
HasOne::make('Instructor Profile'),