如何在 symfony2 中使用学说 findOneBy 方法返回数组而不是对象?

2022-01-16 00:00:00 arrays php symfony doctrine

我有一种情况,我想使用 symfony2 中的学说中的 findOneBy($id) 方法查询数据库.

I have a situation in which I want to query the database with findOneBy($id) method from doctrine in symfony2.

$namePosting = $this->getDoctrine()->getRepository('MyBundle:Users')->findOneById($userPosting);

结果它是一个具有受保护属性的对象.我想直接返回一个数组.如何才能做到这一点 ?

The result it's an object with protected properties. I want to return it directly an array. How can this be done ?

推荐答案

findOneBy(array()) 将始终返回 null 或 object.

findOneBy(array()) will always return null or object.

但您可以使用 findById($userPosting)findBy(array('id' => $userPosting)) 来代替它,它会返回一个数组,例如:

But you can use instead findById($userPosting) or findBy(array('id' => $userPosting)) and it will return an array, e.g.:

$this->getDoctrine()->getRepository('MyBundle:Users')->findById($userPosting))

已编辑

或者你可以在 UserRepository 类中添加一个方法:

    use DoctrineORMEntityRepository;
    use DoctrineORMQuery;

    class UserRepository extends EntityRepository
    { 
        public function getUser($userPosting)
        {
           $qb = $this->createQueryBuilder('u')
             ->select('u')
             ->where('u =:userPosting')->setParameter('userPosting', $userPosting)
             ->getQuery()
             ->getResult(Query::HYDRATE_ARRAY);

           return $qb;
        }   
    }

相关文章