【问题标题】:Doctrine2 - add or update without IdDoctrine2 - 添加或更新没有 Id
【发布时间】:2019-05-31 11:06:24
【问题描述】:

我需要检查我的数据库中的两个字段,以及它们是否存在以更新它们,如果不存在则创建新字段。

我想在不使用 id 作为 post 参数的情况下这样做。我正在尝试使用$firstFiled 参数进行搜索。

会报错

“在 null 上调用成员函数 setFirstName()”

并且数据库中没有任何变化。

我的代码:

public function import($firstName, $lastName)
{
    if($firstName instanceof MyEntity) {

        $new = $this->getMyEntityRepository()->findOneBy([
            'firstName' => $firstName,
            'lastName' => $lastName,
        ]);

    } else {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    $new->setFirstName($firstName);
    $new->setLastName($lastName);
    $this->em->flush();

}

【问题讨论】:

  • 制作新实体对我有用。我有更新现有的问题。 @jeroen

标签: php database symfony doctrine-orm


【解决方案1】:

那段代码对我来说没有多大意义;不是条件,也不是嵌套的 MyEntity 对象。

您可能想要的是寻找并获取一个对象,或者如果没有找到则实例化一个新对象。这是假设名字和姓氏实际上不是同一类的实例。

编辑:请注意,您需要实际的名字和姓氏才能在存储库中找到实体。

比如:

public function import($firstName, $lastName, $newFirstName, $newLastName)
{
    # Get entity from the repository using the current values
    $new = $this->getMyEntityRepository()->findOneBy([
        'firstName' => $firstName,
        'lastName' => $lastName,
    ]);

    # If no entity is found, create a new one
    if(!$new instanceof MyEntity) {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    # Update the existing or new entity with the new values
    $new->setFirstName($newFirstName);
    $new->setLastName($newLastName);
    $this->em->flush();

}

顺便说一句,将你的类和变量重命名为它们实际代表的东西,会更容易发现这样的逻辑错误。

【讨论】:

  • 谢谢你,因为它更有意义。您的代码部分有效,因为它正在创建缺少的实体但不更新现有的实体。 @jeroen
  • @develops 回过头来看,这其实很符合逻辑:如果你发送一个新的 firstname 或 lastname,将找不到实体,所以总是会生成一个新的。如果要根据名称进行更新,则需要同时传递当前和新的名和姓。然后使用当前名称找到实体,然后将属性设置为新值。我已经更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多