Mateusz
Mateusz

Reputation: 331

Use select x from y where z in symfony2 (doctrine)

So I have little problem, I don't know how I can use:

SELECT * FROM product WHERE nazwa = 'Sprite'

in Symfony. Here is my file from "Entity":

<?php

namespace My\MainBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping AS ORM;


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

    /**
     * @ORM\Column(type="integer", length=10)
     */
    protected $cena;
    /**
     * @ORM\Column(type="integer", length=10)
     */
    protected $ilosc;
    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $nazwa;

    public function getCena()
    {
        return $this->cena;
    }

    public function setCena($cena)
    {
        $this->cena = $cena;
    }

    public function getIlosc()
    {
        return $this->ilosc;
    }

    public function setIlosc($ilosc)
    {
        $this->ilosc = $ilosc;
    }

    public function getNazwa()
    {
        return $this->nazwa;
    }

    public function setNazwa($nazwa)
    {
        $this->nazwa = $nazwa;
    }

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

I tried something like this:

$repository = $this->getDoctrine()->getRepository('MainBundle:Product');
                $query = $repository->createQueryBuilder('p')->select('p')->where('p.nazwa == Sprite')->getQuery();
                $test = $query->getResult();

But when I try to use it, I got an error. Somebody have idea what can be wrong?

Upvotes: 0

Views: 106

Answers (2)

Evgeniy Kuzmin
Evgeniy Kuzmin

Reputation: 2462

$repository = $this->getDoctrine()->getRepository('MainBundle:Product');
$result = $repository->findByNazwa('Sprite');

or with QueryBuilder

$query = $repository->createQueryBuilder('p')->select('p')->where('p.nazwa = :nazwa')->setParameter('nazwa', 'Sprite')->getQuery();
 $test = $query->getResult();

Upvotes: 1

Anna Adamchuk
Anna Adamchuk

Reputation: 720

Try this:

$repository = $this->getDoctrine()->getRepository('MainBundle:Product');
                $query = $repository->createQueryBuilder('p');
                $query->where('p.nazwa = :brand')
                      ->setParameter('brand', 'Sprite');
                $test = $query->getQuery()->getResult();

Upvotes: 1

Related Questions