Symfony2, Doctrine 2: getResult Object

2019-06-20 07:00发布

$posts = $em->find('Application\BlogBundle\Entity\Post',1);
print_r ($posts);

Why I got it?

Barii\BlogBundle\Entity\Post Object ( [id:Barii\BlogBundle\Entity\Post:private] => 1 [title:Application\BlogBundle\Entity\Post:private] => something [body:Application\BlogBundle\Entity\Post:private] => content  )

instead of a simple array like this:

array ( [id] => 1,
        [title] => "something",            
        [body] => "content"  )

I use it with Symfony 2.

1条回答
该账号已被封号
2楼-- · 2019-06-20 07:47

You have a couple options here. As far as I know, you can't find results as arrays from entity repositories by default. Instead, you can do one of two things:

First, you could implement a toArray() method on your entity object (perhaps through a mapped superclass) that simply returns an array of properties.

Second, you could use Doctrine Query Language to pull the information that you need using the getArrayResult() method, perhaps something like this:

$query = $em->createQuery('SELECT p FROM Application\BlogBundle\Entity\Post p WHERE p.id=:pid');
$query->setParameter('tid', $postId);
$result = $query->getArrayResult(); // shortcut for $query->getResult(Query::HYDRATE_ARRAY);

More in-depth documentation on DQL can be found here.

查看更多
登录 后发表回答