码迷,mamicode.com
首页 > 其他好文 > 详细

Symfony3 查询搜索功能DQL语句like查询

时间:2017-02-07 01:01:52      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:search   cti   esc   sts   pre   eth   method   his   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查询

标签:search   cti   esc   sts   pre   eth   method   his   like   

原文地址:http://www.cnblogs.com/Amos-Turing/p/6372136.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!