如果uid存在,则更新值

时间:2019-09-12 18:44:58

标签: php symfony symfony4

我想更新MySQL数据库的值。

如果在数据库中找不到具有uid的用户,则应添加一个新行,其值分别为uidfirstname,但是如果uid存在于数据库中,仅应更新列first_name的值。

这是我到目前为止所拥有的:

$em = $this->getDoctrine()->getManager();
$personal = new Personal();
$personal->setUid($uid);
$personal->setFirstName($value);

$em->persist($personal);
$em->flush();

这只会添加一个新行,但是如何更新值?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

    $em = $this->getDoctrine()->getManager();
    $search = $this->getDoctrine()->getRepository(Personal::class)->findBy(array("uid" => $uid));
    if (count($search) == 0) {
        $personal = new Personal();
        $personal->setUid($uid);
    } else {
        $personal = $search[0];
    }
    $personal->setFirstName($value);

    $em->persist($personal);
    $em->flush();