TP5.1 簡單使用搜索器withSearch()


一般來說要實現 搜索欄 的多條件搜索功能,傳統我們是使用where數組條件添加的

 

注意TP5.1的where數組格式 和TP5.0不同  (大坑!)

$title = Request::param('title');
        $start = $this->request->start_time;
        $end = $this->request->end_time;

        $where[] = ['status', '=', '1'];             //初始查詢條件

        if (!empty($start) && !empty($end)) {
            $where[] = [
                ['create_time', 'between time', [intval($start), intval($end)]],   //添加時間查詢
            ];
        }

        if (!empty($title)) {
            $where[] = [
                ['title', 'like', '%' . $title . '%'],       //添加標題查詢
            ];
        }

        $list = NewsModel()::
        field("id,title,create_time")
            ->where($where)
            ->order('create_time desc')
            ->select();

 

使用搜索器,但時間 和 值為單獨0 的查詢建議用where[ ]

 

 
        

先在模型定義

//定義搜索器
    public function searchTitleAttr($query,$value,$data)
    {
        return $value ? $query->where('title','like','%'.$value.'%') : "" ;
    }

 

控制器中使用  搜索器 + where數組

 

public function test( )
    {
        $limit = $this->request->limit ?? 9999;
        $page = $this->request->page ?? 1;

        $start = $this->request->start_time;
        $end = input('end_time');
        $title = $this->request->title;
        
        $where[] = ['status', '=', '1'];
        if (!empty($time1) && !empty($time2)) {     // 時間搜索
            $where[] = [
                ['create_time', 'between time', [intval($start), intval($end)]],
            ];
        }

        $list = ProductModel::alias('a')
            ->leftJoin('class b', 'a.class_id = b.id')
            ->where($where)
            ->field('a.id,class_id,title,imgs_url,b.type_name')
            ->withSearch(['title'], [
                'title' => $title,
            ])
            ->order('a.id desc')
            ->limit($limit)->page($page)
            ->select()->toArray();

        return jsonApi($list,'查詢成功');
    }

 

 

Join聯表查詢也可以使用

public function test()
    {
        $class_id = $this->request->class_id;
        $title = $this->request->title;

        $list = ProductModel::alias('a')
            ->leftJoin('classification b', 'a.class_id = b.id')
            ->where('a.class_id = b.id')
            ->field('a.id,class_id,title,b.type_name')
            ->withSearch(['class_id', 'title'], [  //哪個表的字段就在哪個模型定義搜索器
                'class_id' => $class_id,
                'title' => $title,
            ])
            ->order('a.id desc')
            ->select()->toArray();
        return $list;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM