Allow querying on cusotm fields fieldname directly by column name

This commit is contained in:
snipe
2026-05-26 22:51:46 +01:00
parent f29846ec20
commit ef64210ed2
2 changed files with 30 additions and 0 deletions
@@ -371,6 +371,12 @@ class AssetsController extends Controller
$assets->where('assets.order_number', '=', strval($request->input('order_number')));
}
foreach ($all_custom_fields as $field) {
if ($request->filled($field->db_column_name())) {
$assets->where($field->db_column_name(), '=', $request->input($field->db_column_name()));
}
}
// This is kinda gross, but we need to do this because the Bootstrap Tables
// API passes custom field ordering as custom_fields.fieldname, and we have to strip
// that out to let the default sorter below order them correctly on the assets table.
@@ -4,6 +4,7 @@ namespace Tests\Feature\Assets\Api;
use App\Models\Asset;
use App\Models\Company;
use App\Models\CustomField;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Testing\Fluent\AssertableJson;
@@ -168,6 +169,29 @@ class AssetIndexTest extends TestCase
->assertResponseContainsInRows($assetB, 'asset_tag');
}
public function test_assets_can_be_filtered_by_custom_field()
{
$this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
$field = CustomField::factory()->create();
$matchingAssets = Asset::factory()->count(3)->hasMultipleCustomFields([$field])->create();
foreach ($matchingAssets as $asset) {
$asset->{$field->db_column_name()} = 'target-value';
$asset->save();
}
// These assets have a null value for the custom field column and should not be returned
Asset::factory()->count(2)->create();
$this->actingAsForApi(User::factory()->superuser()->create())
->getJson(route('api.assets.index', [
$field->db_column_name() => 'target-value',
]))
->assertOk()
->assertJson(fn (AssertableJson $json) => $json->has('rows', 3)->etc());
}
public function test_gracefully_handles_malformed_filter()
{
$this->actingAsForApi(User::factory()->viewAssets()->create())