【问题标题】:How to insert value in the table having it primary key in symfony如何在具有symfony主键的表中插入值
【发布时间】:2021-05-28 07:54:21
【问题描述】:

我想在表中插入一个已经定义了 id 的值,该值在教义 symfony 中具有自动递增列 id(PK)。

【问题讨论】:

  • 您好,请在发布问题之前阅读此内容stackoverflow.com/help/how-to-ask 您的问题不符合 StackOverflow 标准,因为它缺乏细节且过于抽象。

标签: symfony orm doctrine


【解决方案1】:

您可以临时更改 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();

【讨论】:

    【解决方案2】:

    注意:通常您不应更新数据库中现有行的 id。
    但是.. 假设您的实体看起来有字段:IDnameValue

    $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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 2014-07-02
      • 2019-01-14
      • 2010-11-25
      相关资源
      最近更新 更多