简体   繁体   中英

INSERT query with doctrine

Good morning all, I am on a project under symfony4 ' I made an association membership management application. Until now when I wanted to update my membership list with a csv file I did it directly in phpMyAdmin. I have a staging table which I called 'import_csv'. I import my csv file on this table and thanks to two requests I add and update my membership list. But I would like to create an admin interface to do the same. I managed to create the import management of my csv file on my intermediate table. I would like to transcribe my SQL queries into my Symfony Controller and this is where I am blocking. My first SQL query to add new members located on my table:

INSERT INTO adherent
(last_name,first_name,to_number,born)
  
SELECT
import_csv.last_name,import_csv.first_name,iimport_csv.to_number,import_csv.born
FROM import_csv LEFT JOIN adherent ON import_csv.to_number=adherent.to_number
WHERE adherent.to_number IS NULL

I tried a lot of things but I can't do it:

/**
     * @Route("import/insert", name="import_insert")
     */
public function import_insert(ObjectManager $manager)
{
  
    $qb = $manager->createQueryBuilder();
    $qb ->select('import_csv.last_name,import_csv.first_name,import_csv.to_number,import_csv.born')
        ->from('\App\Entity\Import_csv','i')
        ->leftjoin('\App\Entity\Adherent on i.to_number=a.to_number','a')
        ->where('a.to_number IS NULL');
  
        $adherent = new \App\Entity\Adherent();
  
        $manager->persist($adherent);
        $manager->flush();
  
    return $this->redirectToRoute('import_csv');
}

Thank you for any help you could give me.

I used a layer underlying the ORM, the DBAL (for Database Abstraction Layer) which allows among other things native queries.

use Doctrine\DBAL\Driver\Connection;
use Symfony\Component\HttpFoundation\Response;
...
 
/**
     * @Route("import/insert", name="import_insert")
     */
public function import_insert(Connection $connection): Response
{
 
    $users = $connection->fetchAll('INSERT INTO adherent
    (last_name,first_name,to_number,born)
       
    SELECT
    import_csv.last_name,import_csv.first_name,import_csv.to_number,import_csv.born
    FROM import_csv LEFT JOIN adherent ON import_csv.to_number=adherent.to_number
    WHERE adherent.to_number IS NULL');
 
    return $this->redirectToRoute('import_csv');
}

It works. the database takes the value indicate but the return does not take place and I have this error: SQLSTATE[HY000]: General error

It's good I found.

$connection->exec('INSERT INTO adherent
    (last_name,first_name,to_number,born)

exec and no fetchAll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM