Answer the question
In order to leave comments, you need to log in
Undefined Index when trying to create a relationship between entities?
There are entities Order
and Product
. There is a ManyToMany connection between them:
App\Entity\Order.php
/**
* @ORM\ManyToMany(targetEntity=Product::class, inversedBy="orders", cascade={"persist"})
*/
private $products;
/**
* @ORM\ManyToMany(targetEntity=Order::class, mappedBy="products")
*/
private $orders;
Order
, there is a method for adding related products:public function addProduct(Product $product): self
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
}
return $this;
}
$product['product']
an instance of the class Product
from the recycle bin. $user = new User();
$password = $this->encoder->encodePassword($user, $data['password']);
$user->setEmail($data['email']);
$user->setUsername($data['username']);
$user->setFirstName($data['first_name']);
$user->setLastName($data['last_name']);
$user->setPassword($password);
$user->setRoles('ROLE_USER');
$em->persist($user);
$em->flush();
//Создаем новый заказ.
$order = new Order();
$order->setUserId($user);
$order->setDate(new \DateTime());
$order->setStatus('new');
$order->setTotal($this->cartService->getTotal());
//Проблемный участок кода. Без него все работает нормально
foreach ($this->cartService->getCartContent() as $product) {
$order->addProduct($product['product']);
}
$em->persist($order);
$em->flush(); // Ошибка на данной строке, судя по дебаггеру Симфони.
Answer the question
In order to leave comments, you need to log in
Such an error comes out if the object in the connection is no longer in the UnitOfWork object. This error can be caused by the wrong version of the doctrine (there were issues on the github), but it seems to me that you should not add flush after each persist here, i.e. it is necessary to make the persistence of the user, orders and added products, and then flash everything once
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question