如何在Laravel 5.4中使用BelongsToMany关系过滤搜索?

时间:2017-04-18 18:07:07

标签: javascript php laravel

我创建了一个过滤器,通过JavaScript从我的搜索中返回数据,此过滤器包含模型,描述,状态,分发器等。我需要在搜索中创建一个搜索字段,返回与产品相关的类别,但是当我运行我的代码,它什么都不返回。

ProdutosController:

r_bachman = pd.read_csv('P00000001-ALL.csv', squeeze=True, low_memory=False,
                        nrows=411 )
cols = r_bachman.columns
r_romney = pd.read_csv('P00000001-ALL.csv', skiprows=range(0,411),
                       na_filter =True, low_memory=False, names=cols)

ProductSearch.js

public function search(Request $request)
    {
        $product = Produtos::query();
        $categoria = Categoria::query();

//        $model = $request->model;
//        $status = $request->status;
//        $distributor = $request->distributor;

        if ($request->isMethod('post'))
        {
            $data = json_decode($request->search_data);
            $descricao;
            $model;
            $status;
            $distributor;
            $stock;
            $image;
            $categoria;

            $descricao = $data->descricao;
            $model = $data->model;
            $status = $data->status;
            $distributor = $data->distributor;
            $stock = $data->stock;
            $image = $data->image;
            $categoria = $data->categoria;

            session(['descricao' => $descricao]);
            session(['model' => $model]);
            session(['status' => $status]);
            session(['distributor' => $distributor]);
            session(['stock' => $stock]);
            session(['image' => $image]);
            session(['categoria' => $categoria]);
        }
        if (strlen(session('descricao')) > 0)
        {
            $product_ids = ProdutosDescricao::where('erp_name', 'LIKE', '%' . session('descricao') . '%')->get();
            $ids = [];

            foreach ($product_ids as $product_data)
            {
                $ids[] = $product_data->erp_productid;
            }

            $product = $product->whereIn('erp_productid', $ids);
        }


        if (strlen(session('model')) > 0)
        {
            $product = $product->where('erp_model', 'LIKE', '%' . session('model') . '%');
        }

        if (strlen(session('status')) > 0)
        {
            $product = $product->where('erp_status', session('status'));
        }


        if (strlen(session('distributor')) > 0)
        {
            $product = $product->where('erp_distributor', session('distributor'));
        }
        if (strlen(session('stock')) > 0)
        {
            if (intval(session('stock')) == 1)
            {
                $product = $product->where('erp_quantity', '>', 0);
            } else
            {
                $product = $product->where('erp_quantity', '=', 0);
            }
        }

        if (strlen(session('image')) > 0)
        {
            $URL_IMAGE = "http://comercio-urbano.s3-website-sa-east-1.amazonaws.com/produtos/marcas/nao_disponivel.jpg";

            if (intval(session('image')) == 0)
            {
                $product_ids = ProdutoImage::where('erp_image', '=', $URL_IMAGE)->get();
                $ids = [];

                foreach ($product_ids as $product_data)
                {
                    $ids[] = $product_data->erp_productid;
                }

                $product = $product->whereIn('erp_productid', $ids);
            }
        }

        if (strlen(session('categoria')) > 0)
        {
            $categoria = $categoria->where('erp_category', session('categoria'));
        }

        $content = $product->paginate(30);

        if ($request->isMethod('post'))
        {
            return view('products.product-table')->with('produtos', $content)->with('categoria', $categoria);
        } else
        {
            return view('products.index')->with('produtos', $content)->with('categoria', $categoria);
        }
    }

Products.index

$(document).ready(function() {

    $(document).on('blur', '#model', function() {
        var model = $('#model').val();
        searchRequest['model'] = model;
        doSearch();
    });

    $(document).on('blur', '#descricao', function() {
        var descricao = $('#descricao').val();
        searchRequest['descricao'] = descricao;
        doSearch();
    });

    $(document).on('blur', '#status', function() {
        var status = $('#status').val();
        searchRequest['status'] = status;
        doSearch();
    });

    $(document).on('blur', '#distributor', function() {
        var distributor = $('#distributor').val();
        searchRequest['distributor'] = distributor;
        doSearch();
    });

    $(document).on('blur', '#stock', function() {
        var stock = $('#stock').val();
        searchRequest['stock'] = stock;
        doSearch();
    });

    $(document).on('blur', '#image', function() {
        var image = $('#image').val();
        searchRequest['image'] = image;
        doSearch();
    });

    $(document).on('blur', '#categoria', function(){
       var categoria = $('#categoria').val();
       searchRequest['categoria'] = categoria;
       doSearch();
    });

});

$(document).on('click', '#clean-form-button', function() {
    $('#descricao').val("");
    $('#model').val("");
    $('#distributor').val("");
    $('#status').val("");
    $('#stock').val("");
    $('#categoria').val("");
    searchRequest = {
        'descricao': '',
        'model': '',
        'distributor': '',
        'status': '',
        'stock': '',
        'image': '',
        'categoria':'',
    };
    doSearch();
});

function IsEmpty(str)
{
    if ( typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g, "") === "" )
    {
        return true;
    }
    else
    {
        return false;
    }
}

function doSearch() {
    $.post(postSearch, {
        'search_data': JSON.stringify(searchRequest),
        '_token': $('meta[name=csrf-token]').attr('content'),
    }
    , function(data) {
        $('#product-table').html(data);
    });
}


$("#model").html('<img src="https://mir-s3-cdn-cf.behance.net/project_modules/disp/1f430a36197347.57135ca19bbf5.gif" alt="Wait" />');
$('#message').load('index.php?pg=ProductSearch', null, function() {
  $("#model").html('');
});
$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }
});

产品table.blade.php

<select class="selectpicker" data-live-search="true" id="erp_categoryid" name="erp_categoryid">
          @foreach($categorias as $categoria)
        <option data-tokens="{{$categoria->erp_name}}" value="{{$categoria->erp_categoryid}}" @if(session('categoria') == "{{$categoria->erp_categoryid}}") selected @endif>{{$categoria->erp_name}}</option>
          @endforeach
        </select>

模型

<td>@foreach($produto->categoria as $categoria)
      {{$categoria->erp_name}}
      @endforeach
    </td>

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

因为您是从Javascript调用它,所以需要从控制器返回JSON。

if ($request->isMethod('post')) {
    return response()->json(compact('content', 'categoria');
} else {
    return view('products.index')->with('produtos', $content)->with('categoria', $categoria);
}

如果它返回一些结果,您可以检查您的控制台。从该响应中,您可以构建您的html。