Filip Svoboda
Filip Svoboda

Reputation: 23

doctrine: many to many relation with join table: how to add WHERE condition

I have three tables:

Clients: (id, name, ...)

Files: (id, filename, type, data)

and join table:

Clients2Files (id, id_clients, id_files, created_at, deleted_at)

in php class Clients I want to get access to all client's files, but only to the files that hasn't been deleted (in sql speak WHERE deleted_at IS NULL)

Now I have code like this (in entity class Client), which selects all (even deleted) files:

/**                                                                         
* @ManyToMany(targetEntity="File")                                          
* @JoinTable(name="Clients2Files",                                  
*      joinColumns={@JoinColumn(name="id_clients", referencedColumnName="id")},
*      inverseJoinColumns={@JoinColumn(name="id_files", referencedColumnName="id")}
*      )                                                                    
*/                                                                          
private $files;              

How can I add condition WHERE deleted_at IS NULL to this doctrine code? To select only files that are not "deleted".

Upvotes: 2

Views: 6297

Answers (1)

ziad-saab
ziad-saab

Reputation: 20269

The annotations you added don't actually "SELECT" anything. All they do is tell Doctrine about your objects and their relations. What you want to do is:

$qb = $em->createQueryBuilder();
$qb->select('clients, files')
   ->from('Clients', 'clients')
   ->join('c.files', 'files')
   ->where('files.deleted_at IS NULL');

If you find yourself doing this often, and are using Doctrine 2.2+, you can take a look at filters: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html

Upvotes: 1

Related Questions