学说 - 有条件的和在查询中

时间:2016-09-12 15:23:57

标签: php laravel doctrine-orm

我想在我的函数中绑定一个条件。我有一个功能MarketersGet给我营销人员的名字。这是我的代码:

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;
}

我想以 $ marketerId 为条件,如果它有值我添加

->andWhere(' model.id = '.$marketerId)

我试过这样:

  $result = $userRepository
        ->selectFrom(' model ')
        ->where(' model.rolesRole = '.$marketerRole);
        if ($marketerId != '')
            $result->andWhere(' model.id = '.$marketerId);
        $result->getQuery()
        ->getResult();

以上结果是:

[]
No Properties

实际上,如果我将以及默认查询放在这里:

    $result = $userRepository
        ->selectFrom(' model ')
        ->where(' model.rolesRole = '.$marketerRole)
        ->andWhere(' model.id = '.$marketerId)
        ->getQuery()
        ->getResult();

真正的结果是这样的:

{name: "blah blah", id: 28}

我的条件查询肯定是假的,有什么建议可以解决吗?

2 个答案:

答案 0 :(得分:0)

无法判断这是否会产生任何影响,但您可以尝试一下:

    $result  = $userRepository
                ->selectFrom(' model ')
                ->where(' model.rolesRole = '. $marketerRole);

    if( isset($marketerId) && $marketerId){
        $result->where(' model.id = '.$marketerId);
    }
    $result->getQuery()
    ->getResult();

答案 1 :(得分:0)

您可以使用此方法。如果marketedId为空字符串-andWhere无效。它总是过去。但是如果它有值,那么将检查model.id条件。

$result = $userRepository
    ->selectFrom(' model ')
    ->where(' model.rolesRole = '.$marketerRole)
    ->andWhere(':marketerId = "''" OR model.id = :marketerId')
    ->setParameter('marketerId', $marketerId)
    ->getQuery()
    ->getResult();