Doctrine/Symfony WHERE clause for reports I'm trying to generate a report from two doctrine entities.

The fields to filter the report are optional. This is the code I've got now and it looks really bad to me. How can I improve this?

public function filter($accountNumber, $companyName, $branchName, $branchManager)
{
    $em = $this-&gt;managerRegistry-&gt;getManager();
    $whereClause = 'WHERE ';

    if (!empty($accountNumber)) {
        $whereClause .= ' u.accountNumber = :acc_number';
    }
    if (!empty($companyName)) {
        $whereClause .= ' AND um.companyName = :company_name';
    }
    if (!empty($branchName)) {
        $whereClause .= ' AND um.branchName = :branch_name';
    }
    if (!empty($branchManager)) {
        $whereClause .= ' AND um.branchAccountManager = :branch_manager';
    }

    $query = $em-&gt;createQuery(
        'SELECT u FROM CarbonUserBundle:User u
        JOIN CarbonUserBundle:UserMeta um WITh u.meta=um.id
       ' . $whereClause
    );

    if (!empty($accountNumber)) {
        $query-&gt;setParameter('acc_number', $accountNumber);
    }
    if (!empty($companyName)) {
        $query-&gt;setParameter('company_name', $companyName);
    }
    if (!empty($branchName)) {
        $query-&gt;setParameter('branch_name', $branchName);
    }
    if (!empty($branchManager)) {
        $query-&gt;setParameter('branch_manager', $branchManager);
    }

    return $query-&gt;getResult();
}
I would suggest using the QueryBuilder

$em = $this-&gt;managerRegistry-&gt;getManager();
$qb = $em-&gt;createQueryBuilder()
    -&gt;select('u')
    -&gt;from(User::class, 'u')
    -&gt;join('u.meta', 'um'); // doctrine generates the join condition automatically


if (!empty($accountNumber)) {
    $qb
        -&gt;andWhere('u.accountNumber = :acc_number')
        -&gt;setParameter('acc_number', $accountNumber)
}
if (!empty($companyName)) {
    $qb
        -&gt;andWhere('u.companyName = :company_name')
        -&gt;setParameter('company_name', $companyName)
}

// and so on...

return $qb-&gt;getQuery()-&gt;getResult();