0

I have view table in my Database, how can I retrieve the data from this views?

I tried to use

$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery('SELECT * FROM my_views');
$result = $query->getResult();

but it doesn't work.

7
  • What you have written inside your createQuery is native SQL while createQuery expects DQL statements. Commented Jul 21, 2015 at 15:11
  • possible duplicate of Execute raw SQL using Doctrine 2 Commented Jul 21, 2015 at 15:17
  • 1
    you can use native sql and map it to an entity. see the doc Commented Jul 21, 2015 at 15:17
  • 1
    yes, see this examples on the doc Commented Jul 21, 2015 at 15:26
  • 1
    Hi @monkeyUser, yes, if you want to map the result in an object you need to write the relative class or use an existing one and map the field as you want Commented Jul 22, 2015 at 8:48

1 Answer 1

3

If you want to perform a simple SQL query, you can do that :

$con = $this->getDoctrine()->getEntityManager()->getConnection();
$stmt = $con->executeQuery('SELECT * FROM my_views');
foreach ($stmt->fetchAll() as $row){
   print_r($row);
}

When you use $em->createQuery(), you need to work with Doctrine entities.

If you want to use the mapping with your view, juste create an entity :

namespace Your\Bundle\Entity;

/**
 * @ORM\Entity
 * @ORM\Table(name="my_view")
 */
class MyView
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     */
    protected $id;

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

    public function getId()
    {
        return $this->id;
    }

    public function getSomeVarcharColumn()
    {
        return $this->someVarcharColumn;
    }
}

And you can query it with DQL like this :

$results = $em->createQuery('
   SELECT v
   FROM YourBundle:MyView v
')->getResult();
Sign up to request clarification or add additional context in comments.

6 Comments

so nice, Can I do also a mapping on Views? I'd like to have getter methods
Thanks for your time. I have to create an entity in "manually" way, I can't have this entity with some function?
You can generate entities from the database, but I'm not familiar with this, so you should read the documentation here : symfony.com/doc/current/cookbook/doctrine/…
I already used symfony.com/doc/current/cookbook/doctrine/… for "classic" table, I don't know if is good also for the views... Thanks again !
After I create the view, I run schema:update and cache:clear and composer update. But it gives me an error No mapping file found named 'MyView.orm.yml' for class 'YourBundle\Entity\MyView. I am using Symfony 2.8...Thanks in advance.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.