I want to bind a condition in my function. I have a function MarketersGet which give me marketers name . Here is my code :
public function MarketersGet(string $marketerId = ''):array
{
$marketerId = (int)$marketerId;
$userRoles = config('constantTypes.blah');
$marketerRole = $userRoles['MARKETER'];
$userRepository = App::make( DoctrineUserRepo::class );
$result = $userRepository
->selectFrom(' model ')
->where(' model.rolesRole = '.$marketerRole)
->getQuery()
->getResult();
$marketers = [];
foreach ($result as $user) {
$marketers[] = [
'name' => $user->getUserName(),
'id' => $user->getId()
];
}
return $marketers;
}
I want to conditional on $marketerId, if it has value I added
->andWhere(' model.id = '.$marketerId)
I tried like this :
$result = $userRepository
->selectFrom(' model ')
->where(' model.rolesRole = '.$marketerRole);
if ($marketerId != '')
$result->andWhere(' model.id = '.$marketerId);
$result->getQuery()
->getResult();
Above result is :
[]
No Properties
Actually if I put andWhere in default query like this :
$result = $userRepository
->selectFrom(' model ')
->where(' model.rolesRole = '.$marketerRole)
->andWhere(' model.id = '.$marketerId)
->getQuery()
->getResult();
Real result would be like this :
{name: "blah blah", id: 28}
Surely my conditional query is false , Any suggestion to resolve it?
No way to tell if this might make any difference but you might try it:
$result = $userRepository
->selectFrom(' model ')
->where(' model.rolesRole = '. $marketerRole);
if( isset($marketerId) && $marketerId){
$result->where(' model.id = '.$marketerId);
}
$result->getQuery()
->getResult();
You can use this approach. If marketedId is empty string - andWhere has no effect. It always passing. But if it has value then model.id condition is checked.
$result = $userRepository
->selectFrom(' model ')
->where(' model.rolesRole = '.$marketerRole)
->andWhere(':marketerId = "''" OR model.id = :marketerId')
->setParameter('marketerId', $marketerId)
->getQuery()
->getResult();