Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何检查更新实体(表行)是否成功并返回真/假响应?_Php_Symfony_Symfony 3.4 - Fatal编程技术网

Php 如何检查更新实体(表行)是否成功并返回真/假响应?

Php 如何检查更新实体(表行)是否成功并返回真/假响应?,php,symfony,symfony-3.4,Php,Symfony,Symfony 3.4,嗯。。方法如下: public function likeUnlikeAction($category, $id, $type) { $status = false; $message = ''; $em = $this->getDoctrine()->getManager(); $article = $em->getRepository("AppBundle:Article")->find($id); if ($type ==

嗯。。方法如下:

public function likeUnlikeAction($category, $id, $type)
{
    $status = false;
    $message = '';

    $em = $this->getDoctrine()->getManager();
    $article = $em->getRepository("AppBundle:Article")->find($id);

    if ($type == 'like') {
        $article->setLikes($article->getLikes() + 1);
    } else {
        $article->setLikes($article->getLikes() - 1);
    }

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

    $likes = $article->getLikes();

    $response = array(
        'status' => $status,
        'message' => $message,
        'likes' => $likes
    );

    return new JsonResponse($response);

}

$em->persist()
$em->flush()
返回始终为空时,我如何检查一切是否正常并更新
$message
$status
呢?

如果你能得到你的文章,如果你的getter/setter有效,你就不必担心
$em->persist()
$em->flush()

您可以在找不到文章时设置消息和状态。您还可以比较更新前后的“likes”编号,以查看是否已应用更新


:请注意,不需要调用$em->persist($product)。回想一下,此方法只是告诉条令管理或“监视”$product对象。在本例中,由于您从Doctrine获取了$product对象,因此它已经被管理。

use
try/catch
Hmm。。但是如果有一种方法不更新它,但也不抛出错误?@MorganFreeFarm-基本上没有。如果没有抛出异常,那么您可以确定操作成功了。我建议不要太在意捕捉个别异常。如果您的代码是正确的,那么在大多数情况下,数据库异常应该是真正异常的,并且几乎不可能从中恢复。@Cerad好的,谢谢!感谢您发送有关“坚持”的通知:)