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

grz*_*kmq 4 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');
    }
} 
Run Code Online (Sandbox Code Playgroud)

这是我的实体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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*man 7

您正在调用该find()函数.由于ID是唯一的,您实际上只需要在ID上调用您的方法,如下所示:

$car = $this->getDoctrine()
    ->getRepository('GrupaProjektBundle:Car')
    ->find($id);
Run Code Online (Sandbox Code Playgroud)

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

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