Symfony2 - Doctrine2 Respository - Set Where Condition for All Methods

109 views Asked by At

When working with a repository, all queries to the Foo Entity require the same condition to be set. What I plan to do is set an account_id property on the repository and use this with any find methods, how ever is this the right way to do this?

class FooRepository extends EntityRepository {

public function setAccountId($account_id) {
    $this->account_id = $account_id;
}

public function findOneBy(array $criteria, mixed $orderBy = null)
{
    $criteria += array('account'=>$this->account_id);
    return parent::findOneBy($criteria, $orderBy);
}

}

Or is it better to just update every find method and set the criteria when calling it:

getRepository('Foo')->findOneBy(array('id'=>1,'account_id'=>2));

The repository also contains custom methods for searching Foo, these would also have to include the account_id.

function search($query=null, $current_page = 1, $page_size = 20) {
...
        $qb->andWhere('f.account = :account_id')
            ->setParameter('account_id',$this->account_id);

Using Doctrine Filters

http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html

This seems like it will allow me to manipulate the query when selecting from the Foo Entity. But what about if I am selecting from Bar which has a relationship to Foo, is it possible to add a join when it does not exist using filters?

For example:

SELECT FROM Bar

Should become:

SELECT FROM BAR JOIN Foo WHERE Foo.account_id=x
0

There are 0 answers