【问题标题】:Update a single column更新单个列
【发布时间】:2019-10-20 17:45:50
【问题描述】:

我有一个表格,其中包含 idtechnologycounter 列。如果给定值等于technology 列的值,则应更新该行。即counter(整数)的值加1。如果表中不存在该值,则应创建一个新行。

这是我尝试过的:

$technologiesOfficial = new TechnologiesOfficial();
$technology = $this->getDoctrine()->getRepository(TechnologiesOfficial::class)->findOneBy(array('technology' => $value));

if (!$technology) {
    $technologiesOfficial->setTechnology($value);
    $technologiesOfficial->setCounter(1);
}
else {
    $counter = $technology->getCounter() + 1;
    $technology->setTechnology($technology->getTechnology());
    $technology->setCounter($counter);
}
$this->em->persist($technologiesOfficial);
$this->em->flush();

这是我得到的:

执行“INSERT INTO”时发生异常 技术_官方(技术,计数器,已批准)值(?,?, ?)' 带参数 [null, null, null]:

SQLSTATE[23000]:违反完整性约束:1048 列 “技术”不能为空

if 语句有效,并且将创建一个新行,但 else 部分会带来问题,即使我尝试使用 $technology->setTechnology('hello');

【问题讨论】:

  • 新插入似乎有问题。我说的对吗?
  • @SwaroopDeval 我可以插入。这不是问题,但我无法更新。

标签: php symfony doctrine-orm symfony4


【解决方案1】:

如果没有看到更多代码,我不清楚你想要实现什么,但是这些行:

$counter = $technology->getCounter() + 1;
$technology->setTechnology($technology->getTechnology());
$technology->setCounter($counter);

似乎没有做太多。您正在调用一个 getter 并传入一个 setter,而显然没有改变对象。看起来你可以用这个来完成同样的事情:

$technology->setCounter($technology->getCounter() + 1);

除非您有充分的理由,否则 setTechnology() 不应依赖 getTechnology(),除非首先更改 getTechnology() 的值。

【讨论】:

  • 我只用$technology->setCounter($technology->getCounter() + 1); 尝试过,但我得到了同样的错误。
【解决方案2】:

我找到了解决方案。问题出在persist的参数上。

$technologiesOfficial = new TechnologiesOfficial();
$technology = $this->getDoctrine()->getRepository(TechnologiesOfficial::class)->findOneBy(array('technology' => $value));

if (!$technology) {
    $technologiesOfficial->setTechnology($value);
    $technologiesOfficial->setCounter(1);
    $object = $technologiesOfficial;
}
else {
    $technology->setCounter($technology->getCounter() + 1);
    $object = $technology;
}
$this->em->persist($object);
$this->em->flush();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多