如何在 table 中插入值,它在 symfony 中具有主键
How to insert value in the table having it primary key in symfony
我想在 table 中插入一个已经定义了 id 的值,它在 doctrine symfony 中具有自动递增列 id(PK)。
您可以临时更改 ID 生成器以存储给定的主要 ID,例如:
use App\Entity\YourEntity;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AssignedGenerator;
use Doctrine\ORM\Mapping\ClassMetadata;
$entity = new YourEntity();
$entity->setId(101);
$entity->setSomething('foo');
$entityManager->persist($entity);
// change the ID generator temporarily before flushing
$metadata = $entityManager->getClassMetaData(YourEntity::class);
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$entityManager->flush();
注意:通常您不应更新数据库中现有行的 ID。
但是但是..假设你的实体看起来像有字段:ID
和 nameValue
:
$car = $carsRepository->find(10); // select a car which the id is 10
$car->setId(1025); // note that : by default your entity DOES NOT have a built method setID() so you have to write it.
$car->setNameValue("Opel");
$manager->flush();
我想在 table 中插入一个已经定义了 id 的值,它在 doctrine symfony 中具有自动递增列 id(PK)。
您可以临时更改 ID 生成器以存储给定的主要 ID,例如:
use App\Entity\YourEntity;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AssignedGenerator;
use Doctrine\ORM\Mapping\ClassMetadata;
$entity = new YourEntity();
$entity->setId(101);
$entity->setSomething('foo');
$entityManager->persist($entity);
// change the ID generator temporarily before flushing
$metadata = $entityManager->getClassMetaData(YourEntity::class);
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$entityManager->flush();
注意:通常您不应更新数据库中现有行的 ID。
但是但是..假设你的实体看起来像有字段:ID
和 nameValue
:
$car = $carsRepository->find(10); // select a car which the id is 10
$car->setId(1025); // note that : by default your entity DOES NOT have a built method setID() so you have to write it.
$car->setNameValue("Opel");
$manager->flush();