溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用Laravel實(shí)現(xiàn)ORM帶條件搜索分頁

發(fā)布時(shí)間:2021-05-14 17:16:37 來源:億速云 閱讀:166 作者:Leah 欄目:開發(fā)技術(shù)

如何使用Laravel實(shí)現(xiàn)ORM帶條件搜索分頁?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

查詢構(gòu)造器:

$users = DB::table('users')->where('votes', '=', 100)->get();

或者ORM:

$users = User::where('votes', '=', 100)->all();

當(dāng)有多個(gè)條件時(shí),可以多次調(diào)用where方法:

$articles = Article::where('id','>','10')->where('is_auth','=','1')->where('id','=','14')->paginate(3)

所以,如果需要進(jìn)行多條件搜索分頁,我們可以這么寫:

public function index(Request $request)
  {
    //分類表數(shù)據(jù)
    $sorts = Sortart::all();
    //文章表實(shí)例化
    $article = new Article;
    //搜索條件判斷
    $where = $article;
    if($request->search_sid){
      $where = $where->where('sort_id','=',$request->search_sid);
    }
    if($request->search_title){
      $where = $where->where('title','like','%'.$request->search_title.'%');
    }
    //分頁搜索
    $articles = $where->paginate(3);
    //搜索條件保持
    $articles->sid = $request->search_sid;
    $articles->title = $request->search_title;
    //$articles = Article::where('id','>','10')->where('is_auth','=','1')->where('id','=','14')->paginate(3);
    //dd($articles);
    return view('admin.articles.index',compact('articles','sorts'));
  }

在頁面中,使用url保持分頁條件的方法:

{!! $articles->appends(['search_sid'=>$articles->sid, 'search_title'=>$articles->title])->render() !!}

效果如圖:

如何使用Laravel實(shí)現(xiàn)ORM帶條件搜索分頁

Laravel 是什么

Laravel 是一套簡潔、優(yōu)雅的PHP Web開發(fā)框架。它可以讓你從面條一樣雜亂的代碼中解脫出來;它可以幫你構(gòu)建一個(gè)完美的網(wǎng)絡(luò)APP,而且每行代碼都可以簡潔、富于表達(dá)力。

看完上述內(nèi)容,你們掌握如何使用Laravel實(shí)現(xiàn)ORM帶條件搜索分頁的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI