【发布时间】:2021-05-28 07:54:21
【问题描述】:
我想在表中插入一个已经定义了 id 的值,该值在教义 symfony 中具有自动递增列 id(PK)。
【问题讨论】:
-
您好,请在发布问题之前阅读此内容stackoverflow.com/help/how-to-ask 您的问题不符合 StackOverflow 标准,因为它缺乏细节且过于抽象。
我想在表中插入一个已经定义了 id 的值,该值在教义 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();
【讨论】: