控制器可以搜索名字和姓氏

时间:2019-06-12 14:55:11

标签: symfony doctrine-orm query-builder entitymanager

我正在尝试通过允许该控制器能够使用名字和姓氏进行搜索来使该控制器更加动态。目前,控制器仅按名字,姓氏和电子邮件地址进行搜索。我希望能够在过滤器“ $ filter =克里斯·史密斯”中输入并查询“克里斯·史密斯”的结果。

下面是我的控制器。

公共函数getEventSessionAttendeeAction(请求$ request,$ eventSessionId)     {

    $filterName = 'filter';

    $searchFields = [
        'o.email',
        'a.email',
        'a.firstName',
        'a.lastName',
        'a.barcode1',
        'a.barcode2',
        'a.id',
        'o.id',
        $lname = 'a.lastName',
        $fname = 'a.firstName'
    ];

    $filter = $request->get('filter');
    $match_level = 0;

   if ( filter_var($filter, FILTER_VALIDATE_EMAIL)) {
    $searchFields = [
        'a.email'
    ];
    $match_level = 1;

    }elseif(preg_match('/^[a-zA-Z\-]*$/', $filter)){
      $searchFields = [
         'a.lastName',
         'a.firstName'
     ];
      $match_level = 2;
   }else{
       $lname = 'a.lastName';
       $fname = 'a.firstName';
   }



    try {
      /** @var ApiEntity\EventSession $eventSession */
//          $eventSession = $this->get('doctrine')->getRepository('KCMApiBundle:EventSession')->findOneById($eventSessionId);
//          $eventAttendees = $this->getEventSessionAttendeesCheckedIn($eventSession);

        $em = $this->getDoctrine()->getManager();
        $qb = $em->createQueryBuilder();
           $qb ->select('a.firstName, a.lastName, a.relationship, a.dateOfBirth, a.barcode1, a.phoneNumber, ea.address1, ea.address2, ea.city, ea.state, ea.country, ea.postal, s.name, s.keynoteSpeaker, ci.created, \'checkin\' AS event')
            ->from('KCMApiBundle:EventSessionCheckin', 'ci')
            ->innerJoin('ci.eventSession', 's')
            ->innerJoin('ci.eventAttendee', 'a')
            ->leftJoin('a.eventAttendeeAddresses', 'ea')
            ->where($qb->expr()->andX(
               $qb->expr()->eq('ci.eventSession', $qb->expr()->literal($eventSessionId))
           ));
//                ->where('ci.eventSession = :sessions')
//                ->groupBy('a.id', 's.id')
//                ->setParameter('sessions', $eventSessionId)



        $expr = $qb->expr()->orX();

        foreach ($searchFields as $field){
            if ($match_level === 1){
                $literalFilter = $filter;
                $expr->add($qb->expr()->like($field, $qb->expr()->literal($literalFilter)));
            }elseif ($match_level === 2){
                $literalFilter = $filter;
                $expr->add($qb->expr()->eq($field, $qb->expr()->literal($literalFilter)));
            }else{
                $literalFilter = $filter;
                $expr->add($qb->expr()->concat($lname, $qb->expr()->concat($qb->expr()->literal($literalFilter), $fname)));
            }
        }

        $qb->andWhere($expr);

        $results = $qb->getQuery()->getResult();

        if ($results) {

            return $this->getApi()->serialize($results);

        }

        return new Response(null, Response::HTTP_NOT_FOUND);

    } catch (\Exception $e) {
        $this->get('logger')->error($e->getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

orX()允许您使用Doctrine进行条件语句。

例如如果您想要蓝色或红色的汽车:

$qb = $this->createQueryBuilder('cars');

$firstCondition = $qb->expr()->eq('cars.color', 'blue');
$secondCondition = $qb->expr()->eq('cars.color', 'red'); 

$qb->where($qb->expr()->orX($firstCondition, $secondCondition));
$qb->setParameter('blue', 'blue');
$qb->setParameter('red', 'red');

$result = $qb->getQuery()->getResult();

您可以通过执行以下操作获得相同的结果:

$qb = $this->createQueryBuilder('cars');

$qb
    ->where('cars.color = :blue')
    ->orWhere('cars.color = :red')
    ->setParamters([
        'blue' => 'blue',
        'red' => 'red',
    ])
;

$result = $qb->getQuery()->getResult();