Okipa / laravel-table

Generate tables from Eloquent models.
MIT License
546 stars 65 forks source link

Search concatenated columns #41

Closed cawecoy closed 4 years ago

cawecoy commented 4 years ago

Hi.

When I try to search users' name and surname together (like "Cawe Coy Rodrigues Marega" where users.name = 'Cawe Coy' and users.surname = 'Rodrigues Marega') I get "No results were found."

$table = (new \Okipa\LaravelTable\Table)
            ->model(\App\User::class)
            ->routes([
                'index'   => ['name' => 'admin.users.index'],
                'show'   => ['name' => 'admin.users.show'],
            ])
            ->query(function($query){
                $query->select('users.*');
                $query->addSelect(\DB::raw("CONCAT(name, ' ', surname) as full_name"));
            });
            $table->column('full_name')->sortable()->searchable('users', ['name', 'surname']);

I also tried the code below (it might be the best solution), but it throws an error:

$table->column('full_name')->sortable()->searchable();

Same for the codes below:

$table->column('full_name')->sortable()->searchable('users', ['full_name']);

$table->column('full_name')->sortable()->searchable('users', [\DB::raw("CONCAT(name, ' ', surname)")]);

How can I search concatenated columns?

Okipa commented 4 years ago

This is a normal behaviour because this package works as an eloquent table builder.

In your case, you should do this :

$table->column('full_name')->searchable(null, ['name', 'surname']);

However, in your case, I think I would simply add 2 columns because I don't see the real benefit to regroup name and surname and it would provide more sorting options :

table->column('name')->sortable()->searchable();
table->column('surname')->sortable()->searchable();