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

时间:2019-06-12 21:19:15

标签: rest api symfony doctrine symfony-http-foundation

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

下面是我的控制器。

public function getEventSessionAttendeeAction(request $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 */


    $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))
       ));



    $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());
}
}

0 个答案:

没有答案