【问题标题】:Attempted to call an undefined method named "flush"试图调用名为“flush”的未定义方法
【发布时间】:2018-01-08 11:41:02
【问题描述】:

我使用:composer require annotations 然后
公共函数 editAction(Product $product){

//        echo '<pre>';
//        print_r($product);

        if(!$product){
            throw $this->createNotFoundException("No product found for id:".$product->getId());
        }
        $product->setName('New product name!');
        $product->flush();
        return $this->redirectToRoute('product_show',[
            'id'=>$product->getId()
            ]);

    }

$product 对象包含 Entity 内的所有属性,但 flush() 方法被视为未定义。这是错误消息:

Attempted to call an undefined method named "flush" of class "App\Entity\Product".

我解决了这个问题:

/**
 * @Route("/product/edit/{id}")
 */
public function updateAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository(Product::class)->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    $product->setName('New product name!');
    $em->flush();

    return $this->redirectToRoute('product_show', [
        'id' => $product->getId()
    ]);
}

但我想用更少的代码来做,因为我可以传递 $product 对象。为什么第一种方法失败了?

注意:我正在使用 symfony4。

【问题讨论】:

  • 为什么你使用 $product->flush() 而不是 $em->flush();
  • @abdussattarbhuiyan,您的问题解决了吗?
  • 奇怪!为什么投反对票,伙计?我想我的 symfony 之旅会因为这个社区的指导而变得愉快。

标签: symfony doctrine-orm orm entity entitymanager


【解决方案1】:

你需要得到manager,并在上面调用flush,而不是直接调用flush()到实体对象

喜欢:

$em = $this-getDoctrine()->getManager();
$product = new Product();
$product->setName('New product name!');
$em->flush();

【讨论】:

    【解决方案2】:

    $product-&gt;setName('New product name!'); 行下遵循以下代码:

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

    【讨论】:

    • 我认为他想要UPDATE 而不是INSERT
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2015-12-20
    • 2018-12-15
    相关资源
    最近更新 更多