findByExample in Doctrine

后端 未结 3 1206
醉话见心
醉话见心 2021-02-19 03:01

Is there a method in Doctrine like Hibernate\'s findByExample method?

thanks

3条回答
  •  不要未来只要你来
    2021-02-19 03:39

    You can use the findBy method, which is inherited and is present in all repositories.

    Example:

    $criteria = array('name' => 'someValue', 'status' => 'enabled');
    $result = $em->getRepository('SomeEntity')->findBy($criteria);
    

    You can create findByExample method in one of your repositories using a definition like this:

    class MyRepository extends Doctrine\ORM\EntityRepository {
        public function findByExample(MyEntity $entity) {
            return $this->findBy($entity->toArray());
        }
    }
    

    In order for this to work, you will have to create your own base class for the entities, implementing the toArray method.

    MyEntity can also be an interface, which your specific entities will have to implement the toArray method again.

    To make this available in all your repositories, ensure that you are extending your base repository class - in this example, the MyRepository one.

    P.S I assume you are talking about Doctrine 2.x

提交回复
热议问题