Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findByExample in Doctrine

Tags:

php

orm

doctrine

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

thanks

like image 737
rizidoro Avatar asked Jan 13 '10 13:01

rizidoro


People also ask

What is a repository Doctrine?

A repository mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. In Doctrine, a repository is a class that concentrates code responsible for querying and filtering your documents.

How do I know my Doctrine version?

Check out the file vendor/doctrine/orm/lib/Doctrine/ORM/Version. php , there is a constant in there that shows the version. It's also accessible from a running app but this is easier.

What is Doctrine Symfony?

Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.

What is a entity in Symfony?

Well, entity is a type of object that is used to hold data. Each instance of entity holds exactly one row of targeted database table. As for the directories, Symfony2 has some expectations where to find classes - that goes for entities as well.


1 Answers

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

like image 90
Nikola Petkanski Avatar answered Oct 08 '22 19:10

Nikola Petkanski