如何在枢轴 table 上应用过滤器?

How to apply filter on pivot table?

类别模型

public function lists(){
    return $this->belongsToMany(Listing::class);
}

上市型号

public function categories(){
    return $this->belongsToMany(Category::class)
        ->withPivot(['category_id','listing_id']); 
}

控制器:当我 dd 这个查询时,我得到了列表 table 中的所有列表,但我只想得到那些具有这些类别的列表。

if($request->categories){
    $var = $request->categories; // data in array 1,2,3
    $lists = Listing::with(['categories' => function ($query) use($var) {
        $query->whereIn('category_id',$var);
    }])->get();
    dd($lists);

此代码运行完美

 $state=$request->state;
    $type=$request->type;
    $categories=$request->categories;
    if(!$request->all()==null){
        $lists = Listing::when($state!=Null,function ($query) use ($state) {
            return $query->where('state', $state);})->
        when($type!=Null,function ($query) use ($type) {
            return $query->where('type', $type);});
       if(!$categories==null){
           foreach($categories as $var){
               $lists->whereHas('categories',function($q) use($var){
                   $q->where('category_id',$var);
               });
           }
       }
     $lists=$lists->get();
    }

为您的 table

提供一些 ID 名称
<table id="userTable" style="display: table;" class="table table-responsive text-center table-striped table-hover">

然后使用以下脚本:

<script type="text/javascript">
    
    $(document).ready(function() {
    var table = $('#userTable').DataTable( {
        scrollY:        "400px",
        scrollX:        true,
        scrollCollapse: true,
        paging:         true,
        columnDefs: [ {
            sortable: false,
            "class": "index",
            targets: 0
        } ],
        order: [[ 4, 'dsc' ]],
        fixedColumns: true
    } );
 
    table.on( 'order.dt search.dt', function () {
        table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();
} );


   </script>

现在您必须能够搜索、过滤和重新排序您的 table。