I'm making an inlog form where the user can decide to use this username or email address in combination with its password. So normally it would something like: ((username OR email) AND password) in SQL. Used the following controller code only don't know how to add the OR function.
$user = $this->getDoctrine()
->getRepository('Bundle:CusUser')
->findOneBy(
array('username' => $user->getUsername(), 'email' => $user->getUsername(), 'password' => $user->getPassword())
);
For both is getUsername used as this is the flied in the form.
Actually there is no ->orBy(...)
method in the default doctrine EntityRepository
.
You can find all methods available in the API of this class.
Instead, use a QueryBuilder
:
$query = $this->getDoctrine()
->getRepository('Bundle:CusUser')
->createQueryBuilder('u')
->select('u')
->where('u.username = :username')
->orWhere('u.email = :email')
->setParameter('username', $user->getUsername())
->setParameter('email', $user->getEmail())
->getQuery();
// Get the first result
$user = $query->setMaxResults(1)->getSingleResult();
Put it in a custom EntityRepository
and use it with an array of arguments that you use as where
and orWhere
statement's parameters. e.g. :
public function findByOrBy(array $parameters)
{
$query = $this->getEntityManager()->createQueryBuilder();
// ...
foreach ($parameters as $property => $value) {
$query
->orWhere($property.' = :'.$property)
->setParameter($property, $value)
// ...
}
}
You can find the list of the available methods (almost all correspondences of native SQL methods) in the QueryBuilder
API.