Symfony3 查询搜索功能DQL语句like查询
Posted 01coding.com
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Symfony3 查询搜索功能DQL语句like查询相关的知识,希望对你有一定的参考价值。
//前台页面代码
<form method="GET" action="{{ path(‘staff_index‘) }}" name="searchterm"> <label> <input name="searchterm" type="text" value="" placeholder="输入名称" > </label> <input type="submit" value="查询"> </form>
/** * Lists all customer entities. * * @Route("/", name="staff_index") * @Method("GET") * @Template() */ public function indexAction(Request $request) {
$em = $this->getDoctrine()->getManager();//实体管理 $searchterm = $request->get(‘searchterm‘);//页面参数获取
$page = $request->query->getInt(‘page‘,1); $query = $em->getRepository(‘XinXiBundle:Customer‘)//实体查询 ->createQueryBuilder(‘u‘);
if (!null == $searchterm){//如果参数不为空就执行like查询 $query->where( $query->expr()->like(‘u.name‘, ‘:user‘) ) ->setParameter(‘user‘,‘%‘.$searchterm.‘%‘) ->getQuery() ->getResult(); }else{ $query->orderBy(‘u.id‘,‘desc‘) //否则查询所有列表 ->getQuery(); } $pagination = $this->get(‘knp_paginator‘) //分页功能 ->paginate($query, $page,5); return [ ‘pagination‘ => $pagination, ]; }
多个条件查询时使用 andWhere 如下:
$em = $this->getDoctrine()->getManager(); $searchterm = $request->get(‘searchterm‘); $page = $request->query->getInt(‘page‘,1); $query = $em->getRepository(‘XinXiBundle:Customer‘) ->createQueryBuilder(‘u‘); if (!null == $searchterm){ $query ->andWhere($query->expr()->like(‘u.name‘, ‘:user‘)) ->andWhere(‘u.status = :status‘) ->setParameter(‘status‘,true) ->setParameter(‘user‘,‘%‘.$searchterm.‘%‘) ->getQuery() ->getResult(); }else{ $query->orderBy(‘u.id‘,‘desc‘) ->where(‘u.status = :status‘) ->setParameter(‘status‘,true) ->getQuery(); }
实体关联查询
$em = $this->getDoctrine()->getManager(); $searchterm = $request->get(‘searchterm‘); $page = $request->query->getInt(‘page‘, 1); $query = $em->getRepository(‘XinXiBundle:Finance‘) ->createQueryBuilder(‘f‘); if (!null == $searchterm) { $query ->join(‘f.customer‘ , ‘customer‘) //关联实体属性 现在别名为customer ->andWhere($query->expr()->like(‘customer.name‘, ‘:name‘))//此时再使用customer.属性值进行like查询 ->andWhere(‘f.status = :status‘) ->setParameter(‘status‘, true) ->setParameter(‘name‘, ‘%‘ . $searchterm . ‘%‘) ->orderBy(‘f.id‘, ‘desc‘) ->getQuery() ->getResult();
以上是关于Symfony3 查询搜索功能DQL语句like查询的主要内容,如果未能解决你的问题,请参考以下文章