亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的第三個條件在搜索中不起作用?

為什么我的第三個條件在搜索中不起作用?

PHP
慕村9548890 2022-08-19 15:58:01
我正在嘗試獲取搜索結果,并且我有以下代碼:public function search(Request $request){     $from = $request->from;    $to = $request->to;    $word = $request->word;      if(empty($word) || $word == null){        $searched = Post::whereBetween('created_at', [$from, $to])->paginate(10);    } elseif(!empty($word) && !empty($from) && !empty($to)){         $searched = Post::where('title', 'LIKE', '%' . $word . '%')        ->orWhere('content', 'LIKE', '%' . $word . '%')        ->orWhere('subtitle', 'LIKE', '%' . $word . '%')        ->whereBetween('created_at', [$from, $to])        ->paginate(10);     } elseif(empty($from) && empty($to) && !empty($word)){        $searched = Post::where('title', 'LIKE', '%' . $word . '%')        ->orWhere('content', 'LIKE', '%' . $word . '%')        ->orWhere('subtitle', 'LIKE', '%' . $word . '%')        ->paginate(10);    }    return view('page.search', compact('searched', 'from', 'to'));}第一個和第二個條件正在起作用,但最后一個條件不起作用。我在這里錯過了什么或做錯了什么?
查看完整描述

1 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

試試這個

  • 例如,如果找到單詞,則使用類似搜索,然后第一個條件為真

  • 如果用戶設置了開始日期和截止日期,則第二個條件為 true

  • 如果用戶同時填寫(單詞和日期),則您的兩個條件都為真。

  • 如果你沒有填寫任何值,那么只得到前10(十)個帖子(沒有條件匹配)

public function search(Request $request){


    $posts = Post::query();

    $from = $request->from;

    $to = $request->to;

    $word = trim($request->word);


    if($word && !empty($word)){

           $posts->where('title', 'LIKE', '%' . $word . '%')

            ->orWhere('content', 'LIKE', '%' . $word . '%')

            ->orWhere('subtitle', 'LIKE', '%' . $word . '%');

    }


    if(!empty($from) && !empty($to)){

        $posts->whereBetween('created_at', [$from, $to]);

    }


    $searched = $posts->paginate(10);


    return view('page.search', compact('searched', 'from', 'to'));

}


查看完整回答
反對 回復 2022-08-19
  • 1 回答
  • 0 關注
  • 123 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號