如何检查数据库中是否存在多条记录(laravel doctrine)

时间:2017-06-08 12:07:38

标签: doctrine-orm doctrine-query

我想确认数据库中是否存在用户集合。所以,说我有一个数组:

$data = [
    [
        'firstName' => 'Alastair',
        'lastName' => 'Appleby'
    ],
    [
        'firstName' => 'Celine',
        'lastName' => 'Wilkinson'
    ]
];

如果存在,我想要返回这两个用户。我似乎无法找到有效地做到这一点的有效方法。我尝试运行本机查询,但没有返回任何内容,我认为这是因为我绑定了参数的方式。我的尝试:

    $where = [];
    $params = [];

    foreach($data as $n => $u) {
        $where[] = '(first_name = ? AND last_name = ?)';
        $params[$n + $n + 1] = $u['firstName'];
        $params[$n + $n + 2] = $u['lastName'];
    }

    $where = implode(' OR ', $where);

    $query = "SELECT * FROM users WHERE $where";

    $q = $this->em->createNativeQuery($query, new ResultSetMapping());
    $q->setParameters($params);

    return $q->getArrayResult();

1 个答案:

答案 0 :(得分:1)

您需要使用查询构建器表达式方法,如此;

$qb = $this->em->createQueryBuilder();

$where = [];
$params = [];

$qb->select('u')
    ->from(User::class, 'u');

foreach($data as $n => $u) {
    $where[] = $qb->expr()->andX(
        $qb->expr()->eq('u.firstName', ":firstName$n"),
        $qb->expr()->eq('u.lastName', ":lastName$n")
    );

    $params["firstName$n"] = $u['firstName'];
    $params["lastName$n"] = $u['lastName'];
    }

$qb->where($qb->expr()->orX(
    $where
))->setParameters($params);

return $qb->getQuery()->getArrayResult();