A
A
Anton Seredny2020-11-10 20:08:33
symfony
Anton Seredny, 2020-11-10 20:08:33

Undefined Index when trying to create a relationship between entities?

There are entities Orderand Product. There is a ManyToMany connection between them:

App\Entity\Order.php

/**
 * @ORM\ManyToMany(targetEntity=Product::class, inversedBy="orders", cascade={"persist"})
 */
private $products;


App\Entity\Product.php

/**
 * @ORM\ManyToMany(targetEntity=Order::class, mappedBy="products")
 */
private $orders;


In essence 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;
}


Here is the code that I use to create a user, an order, and link products from the user's basket to the order. This is where the error occurs. To $product['product']an instance of the class Productfrom the recycle bin.

App\Controller\CheckoutController.php

$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(); // Ошибка на данной строке, судя по дебаггеру Симфони.


Below is a screenshot of the error. As far as I understand, he cannot correctly put down the links between the order and the products from the order.

5faac903b64cd120656146.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2020-11-10
@smidl

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 question

Ask a Question

731 491 924 answers to any question