php 如何在symfony2中使用教义findOneBy方法返回一个数组而不是对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23681567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:52:37  来源:igfitidea点击:

How to return an array not an object with doctrine findOneBy method in symfony2?

phparrayssymfonydoctrine

提问by irimie andrei

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

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

$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 ?

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

回答by Ioana Hazsda

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

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

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

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

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

Edited

已编辑

Or you can add a method in UserRepositoryclass:

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

    use Doctrine\ORM\EntityRepository;
    use Doctrine\ORM\Query;

    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;
        }   
    }