Symfony2发出变量id以从数据库中获取对象

时间:2016-02-11 20:32:20

标签: php symfony doctrine-orm

我想从数据库$id$name获取,但我得到了这个例外:

  

Grupa \ ProjektBundle \ Entity \ Car

的查询缺少标识符ID

我在实体GeneratedValue(strategy="AUTO")中的Doctrine注释中有Car。 我怎样才能解决这个问题?路由匹配!

此外,我有一个id为1的数据库条目和名称,其中某个URL的值指向图像(http://www.supercarworld.com/images/fullpics/595.jpg)。

这是我的控制器名为 SupercarsController.php

namespace Grupa\ProjektBundle\Controller;

use Grupa\ProjektBundle\Entity\Car;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class SupercarsController extends Controller
{
    public function scAction($id = null, $name = null){
        $car = new Car();
        // $car->setName('http://www.supercarworld.com/images/fullpics/595.jpg');

        // em entity manager
        // $em = $this->getDoctrine()->getManager();
        // $em->persist($car);
        // $em->flush();

        $car = $this->getDoctrine()
        ->getRepository('GrupaProjektBundle:Car')
        ->find($id, $name);
        return $this->render('GrupaProjektBundle:Sc:supercars.html.twig');
    }   

    public function showAction($slug)
    {
        $url = $this->generateUrl('grupa_projekt_supercars',
            array('slug' => 'marka')
            );
        return $this->render('GrupaProjektBundle:Sc:makes.html.twig');
    }
} 

这是我的实体 Car.php

namespace Grupa\ProjektBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
*/
class Car
{   /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    *
    */
    protected $id;

    /**
    * @ORM\Column(type="string")
    *
    */
    protected $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;

        return $id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Car
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

2 个答案:

答案 0 :(得分:7)

您正在正确调用find()函数。由于ID是唯一的,因此您只需要在ID上调用您的方法,如下所示:

$car = $this->getDoctrine()
    ->getRepository('GrupaProjektBundle:Car')
    ->find($id);

但是,如果您愿意, 仍会搜索ID和名称,但您必须将查询更改为:

$car = $this->getDoctrine()
    ->getRepository('GrupaProjektBundle:Car')
    ->findOneBy(array('id' => $id, 'name' => $name));

答案 1 :(得分:4)

只是为了通知其他人:当我尝试使用null值变量调用方法find()时,我收到了相同的错误消息。

我这样做:find($userId)没有意识到$userId == null,而且我收到了错误消息,让我了解了这个主题。

希望能节省一些时间

相关问题