首页 > 解决方案 > Laravel 8 & Yajra Datatables 复杂搜索

问题描述

我有一个获取订单的数据表,并且可以正常工作和显示。我向发起订单的用户展示订单。然后他们只能根据自己的订单进行搜索。现在我需要向用户显示一条消息,如果找到订单但它是由另一个用户发起的,而不是在数据表中显示空结果。这将在输入搜索框后发生,而不是在开始时加载数据表时发生。问题是查询已经按用户 ID 过滤了结果,所以我无法在手动搜索期间更改它。

如果需要,我可以显示代码,但功能非常大,我真的不需要代码,而是这样做的逻辑/方式。

你对我如何做到这一点有什么建议吗?

标签: laravellaravel-8yajra-datatable

解决方案


好吧,也许不是最好的方法,但这就是我解决它的方法:

在控制器中,我检查搜索字段,并对关系运行查询,但仅针对具有与登录用户不同的卖家的订单:

        $otherSeller = "";
        if(!empty($request->search['value']))
        {
            $ordersOtherSeller = Order::where('status_id', "!=", 3)->where('seller_id', '!=', $loggedUser->id)->whereHas('user', function ($q) use ($request){               
            $q->searchFullName($request->search['value']);
            })->first();  

            if($ordersOtherSeller != NULL && $ordersOtherSeller->count() > 0)        
                $otherSeller = $ordersOtherSeller->user->full_name . ' ' . $ordersOtherSeller->seller->full_name;       
        }

我用表的 json 设置了一个自定义变量:

...
->with('otherSeller', $otherSeller)          
->make(true);

然后在数据表 jquery drawCallBack 上,我检查一个填充的字符串,以保证当前用户的查询不会返回结果:

            fnDrawCallback: function( oSettings ) {             
            var api = this.api();   
            if(api.ajax.json().otherSeller != "") 
            {
                $('#alert-info span').text(api.ajax.json().otherSeller);
                $('#alert-info').show();
            }
            else
                $('#alert-info').hide();                
        },

最后是使用更新文本切换 materialert 元素:

  <div id="alert-info" class="materialert info" style="display: none;">
      <i class="material-icons">info</i> <span></span>
      <button type="button" class="close-alert">×</button>
  </div>

推荐阅读