Witam,
jak w Symfony dodać rekordy do kilku tabel jednocześnie? Powiedzmy że mamy tabelę User i Avatar. Przy rejestracji chcę sprawdzić jaką płeć wybrał użytkownik i na tej podstawie zapisać link do zdjęcia do tabeli Avatar, email i hasło do tabeli User i imię oraz płeć do tabeli Specific. W Laravelu zrobił bym to w ten sposób czy podobny sposób
DB::transaction(function () use ($r){
$u = User::create([
'email' => $r->email,
'password' => Hash::make($r->password)
]);
Specific::create([
'user_id' => $u->id,
'name' => $r->name,
'last_name' => $r->last_name,
'sex' => $r->sex
]);
if ($r->sex === 1){
$avatar = '';
}else{
$avatar = '';
}
Avatar::create([
'user_id' => $u->id,
'src' => $avatar
]);
});
tutaj używam formularz
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email')
->add('plainPassword', PasswordType::class, [
// instead of being set onto the object directly,
// this is read and encoded in the controller
'mapped' => false,
'constraints' => [
new NotBlank([
'message' => 'Please enter a password',
]),
new Length([
'min' => 6,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
],
])
->add('agreeTerms', CheckboxType::class, [
'mapped' => false,
'constraints' => [
new IsTrue([
'message' => 'You should agree to our terms.',
]),
],
])
;
}
i kontroler
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $this->redirectToRoute('/');
}
return $this->render('user/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}