V
V
vladislav9972021-06-25 14:48:16
Doctrine ORM
vladislav997, 2021-06-25 14:48:16

How to add a record to an intermediate table without creating a new object?

Can you please tell me how to add an entry to an intermediate table without creating a new object in Symfony?

There is this code:

$subscriber = $em->getRepository(Subscribers::class)->findOneBy(['id' => 1);
$subscriber->addBot($bot); // $bot - это сущность
$em->persist($subscriber);
$em->flush();

And as a result, nothing will happen.
The bottom line is this: a lot of bots (a separate entity) are stored in the database, they have a connection with subscribers - many to many. and the point is that one user can belong to several bots. and when the user is first written to the database, then there is a record in the intermediate table, but if the user wrote to the second bot, then we should not enter it a second time, but should simply add the record to the intermediate table. for this purpose, I put a check on "if it exists, then we do not write it down a second time, but only make an entry in the intermediate table."
complete code

$findSubscriber = $em->getRepository(Subscribers::class)->findOneBy(['subscriber_id' => $subscriber['message']['from']['id']]);

            if(!$findSubscriber) {
                $subscribers = new Subscribers();

                $subscribers->setUsername($subscriber['message']['from']['username']);
                $subscribers->setSubscriberId($subscriber['message']['from']['id']);
                $subscribers->addBot($bot);
                $em->persist($subscribers);
                $em->flush();
                // здесь отрабатывает нормально
            }
            else {
                foreach ($bot->getSubscribers()->toArray() as $botSubscriber) {
                    if ($botSubscriber->getSubscriberId() != $subscriber['message']['from']['id']) {
                        $findSubscriber->addBot($bot);
                        $em->persist($findSubscriber);
                        $em->flush();
                        // не отрабатывает
                    }
                }
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Pushkar, 2021-07-02
@NickPush

here it is necessary to look at the classes that are in the Entity. show me what's there?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question