问题
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);
}
);
But it got error: htmlspecialchars() expects parameter 1 to be string, array given
. How I can fix this?
Thank you very much!
回答1:
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'],
];
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',
];
来源:https://stackoverflow.com/questions/57121402/filter-table-with-a-column-in-laravel-backpack