Laravel背包中带有列的过滤器表 [英] Filter table with a column in Laravel Backpack

查看:51
本文介绍了Laravel背包中带有列的过滤器表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Employee表,其显示如下:

I have a Employee table which display like this:

+-------------------------------+
|  id  |    name    |   code    |
---------------------------------
|  1   | Employee 1 |    A1     |
|  2   | Employee 2 |    A2     |
| ...  |    ...     |   ...     |
+-------------------------------+

我想在此表中按代码列创建过滤器.我的查询将是这样的:

And I want to create a filter by code column in this table. My query will be like this:

SELECT name FROM employee WHERE code LIKE .% $filter %.

我在背包文件中搜索并尝试这样做

I searched in backpack document and trying to do like this

$this->crud->addFilter(
    [
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function () {
        return Employee::select('code')->distinct()->get()->toArray();
    },
    function ($value) {
        $this->crud->addClause('where', 'code', $value);
    }
);

但是出现错误: htmlspecialchars()期望参数1为字符串,数组为给定的.我该如何解决?

But it got error: htmlspecialchars() expects parameter 1 to be string, array given. How I can fix this?

非常感谢!

推荐答案

您的用于生成员工代码列表的代码此刻正在返回这样的数组,而程序包则期望一个字符串数组.

Your code to generate the list of employee codes is returning an array like this at the moment, while the package is expecting an array of strings.

[
    ['code' => 'A1'],
    ['code' => 'A2'],
];

要解决此问题,您需要从数组中 puck code 列,并按以下代码对其进行键控:

To fix the issue, you need to pluck the code column from the array, and key it by the code:

$this->crud->addFilter([
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function() {
        return Employee::select('code')->distinct()->get()->pluck('code', 'code')->toArray();
    },
    function($value) {
        $this->crud->addClause('where', 'code', $value);
    });

这将导致类似以下内容:

This will result in something like:

[
    'A1' => 'A1',
    'A2' => 'A2',
];

这篇关于Laravel背包中带有列的过滤器表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆