使用symfony2在数据库中插入值

时间:2022-10-16 15:13:03

I want to insert values in my table but it doesn't work for me, what should I do?

我想在我的表中插入值,但它对我不起作用,我该怎么办?

class DefaultController extends Controller
{
  public function indexAction($name)
  {
    return $this->render('MyAppLibraryBundle:Default:index.html.twig', array('name' => $name));
  }

  public function createAction()
  {
    $product = new Product();
    $product->setName('A Foo Bar');
    $product->setPrice('19.99');
    $product->setDescription('Lorem ipsum dolor');

    $em = $this->getDoctrine()->getManager();
    $em->persist($product);
    $em->flush();

    return new Response('Id du produit créé : '.$product->getId());
  }
}

1 个解决方案

#1


One possible source of error is that the Product entity cannot be found by the controller. By adding the use MyAppLibraryBundle\Entity\Product; statement (assuming it is in that path) the entity can be found. If this is not the answer, please post the error message(s) you receive.

一个可能的错误来源是控制器无法找到Product实体。通过添加使用MyAppLibraryBundle \ Entity \ Product;声明(假设它在该路径中)可以找到实体。如果这不是答案,请发布您收到的错误消息。

//with this line:
use MyAppLibraryBundle\Entity\Product;

class DefaultController extends Controller
{
....

public function createAction()
{
    $product = new Product();
    $product->setName('A Foo Bar');
    $product->setPrice('19.99');
    $product->setDescription('Lorem ipsum dolor');

    $em = $this->getDoctrine()->getManager();
    $em->persist($product);
    $em->flush();

    return new Response('Id du produit créé : '.$product->getId());
}

}

#1


One possible source of error is that the Product entity cannot be found by the controller. By adding the use MyAppLibraryBundle\Entity\Product; statement (assuming it is in that path) the entity can be found. If this is not the answer, please post the error message(s) you receive.

一个可能的错误来源是控制器无法找到Product实体。通过添加使用MyAppLibraryBundle \ Entity \ Product;声明(假设它在该路径中)可以找到实体。如果这不是答案,请发布您收到的错误消息。

//with this line:
use MyAppLibraryBundle\Entity\Product;

class DefaultController extends Controller
{
....

public function createAction()
{
    $product = new Product();
    $product->setName('A Foo Bar');
    $product->setPrice('19.99');
    $product->setDescription('Lorem ipsum dolor');

    $em = $this->getDoctrine()->getManager();
    $em->persist($product);
    $em->flush();

    return new Response('Id du produit créé : '.$product->getId());
}

}