doujingke4981 2017-04-27 16:25
浏览 63
已采纳

用ajax搜索,在数组中“喜欢”

Please help with search script

$("#search").on("keyup",function(){
    var search=$("#search").val();
    search=search.replace(/  +/g, ' ');
    if(search.length>=1){
        var result=search.split("");
        $.ajax({  
            type: 'POST',  
            url: "{{URL('/searchajax')}}", 
            data: 
                { 
                    search:result
                },
            success: function(data) {
                $("#searchresult").css("display","block");
                if(data.length>0){
                    for(var i=0;i<data.length;i++){
                        $.each(data[i], function( index, value ) {
                            $("#itemssearch").append("<a href='{{URL('/product')}}/"+value.id+"'>\
                                                            <li>"+value.originalname+value.name+"</li>
\
                                                        </a>
\
                                                        ");

                            });
                    }
                }else{
                      ...
                }
            }
        });
    }
});

public function searchajax(Request $request){
    $search=$request->search;
        $return=DB::table("products")
                ->where('originalname', 'like', '%'.$search.'%')
                ->orWhere('name', 'like', '%'.$search.'%')
                ->orderby("products.table_id")
                ->take(5)
                ->get();

    return response()->json($return);
}
  1. if have search word "iphone 7s" how to search first "iphone" then "7s" and get all result in one variable
  2. if have search word "iphone 7s" how to search first "iphone" then "7s" and get all result in one variable
  • 写回答

3条回答 默认 最新

  • dqvy87517 2017-04-27 16:32
    关注

    If I understood you correctly, you want to apply orWhere() pair for each word with foreach:

    $words = explode(' ', $search);
    
    $result = Product::query();
    
    foreach ($words as $word) {
        $result = $result->orWhere('originalname', 'like', '%'.$word.'%')
                         ->orWhere('name', 'like', '%'.$word.'%');
    }
    
    $result = $result->orderby("products.table_id")->take(5)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?