Search for several arguments with Doctrine

2019-09-02 11:26发布

问题:

I'm a total beginner with Symfony2 and I have a problem using Doctrine right. I habe created an entity for an existing database and I can use Doctrine to search within the database using the findById, findByAuthor etc. functions. My next step was to create a HTML form where the user can enter several arguments. My goal is, that Doctrine now searches the database for all entities, who match all/at least one of the arguments. I hoped that I can do this using an entity with the typed in data but I don't know how.

Hopefully you understand what I mean and can help me :)

Greets

回答1:

You will need to do this using custom queries. This is done through DQL mostly.

As for making this seemless, you will need to create yourself a custom repository class if not already done to put the query into. It seems like a bit of a overhead. I went through that phase of looking around for alternatives too. But in the end, it's quite simple.

When asking for the repository for the entity type, Doctrine will just provide you with an instance of your class and it will transparent.



回答2:

For simple conditions, you can use the findBy method. With $em the entity manager

$em->getRepository('YourBundle:YourEntity')->findBy(array(
    'id' => $id, 
    'author' => $author));

More information with the Doctrine documentation

For more complicated conditions, you'll have to use DQL