Skip to content

fix(values): save custom field values without per-field queries - #304

Merged
ManukMinasyan merged 2 commits into
3.xfrom
fix/save-values-without-per-field-queries
Nov 20, 2026
Merged

ManukMinasyan merged 2 commits into
3.xfrom
fix/save-values-without-per-field-queries

Conversation

@ManukMinasyan

@ManukMinasyan ManukMinasyan commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Symptom

Every save of a model with N active custom fields ran 2N extra read queries. In the Relaticle app (Sentry RELATICLE-CRM-7E, 34 events) a PATCH on a task cost 34 queries with 4 fields and 64 with 10. The repeats were select * from custom_field_values where entity_type=? and entity_id=? and (custom_field_id=? and tenant_id=?) and tenant_id=? limit 1 and select * from custom_fields where id=? and active=? and tenant_id=? order by sort_order asc limit 1.

What changed

UsesCustomFields::saveCustomFields() now loads the active fields with their options once, loads the model's existing values for those fields in one query, and matches them in memory by field id (and tenant column when multi-tenancy is on). A missing row is built with customFieldValues()->make(). The loaded CustomField is set on the value's customField relation, so CustomFieldValue::setValue() no longer re-queries it.

saveCustomFieldValue() is split into customFieldValueKey() (the lookup key, unchanged logic) and writeCustomFieldValue() (encryption cast, setValue, save, change tracking). The public method still does firstOrNew and still lets setValue lazy-load the field.

Why this way

The batch path gets its fields from the active, tenant-scoped customFields() query, so handing them to the value is safe. The single-field public method is also called by ImporterBuilder and tests with a field that may have been deactivated since it was loaded. Pre-loading the relation there would skip the "field is inactive" RuntimeException that CustomFieldValueOrphanedRowTest pins, so I left that path alone. My first attempt set the relation in the shared writer and failed those two tests.

The fields are loaded with('options'). Before this PR each value lazy-loaded its own field as a single model, so an app with Model::preventLazyLoading() could read $value->customField->options in a value observer. A field from a multi-row query is a strict model, and that read throws LazyLoadingViolationException. Relaticle's activity log does exactly this, and the first commit broke 53 of its tests. Eager loading costs one query per save and keeps that contract.

Behaviour to know about

  • Null or empty still writes: every active field is iterated and a missing key saves null, so clearing a value is unchanged. Rows are still created for fields the payload does not name, as before.
  • Tenant scoping, the encrypted cast, wasChanged tracking and the updated_at stamp are the same code paths. Model events fire the same way, since each value is still saved individually.
  • A value's customField relation now arrives with options loaded.
  • Per-field writes are unchanged. This only removes the reads.
  • No API change, no migration, no config.

Tests

tests/Feature/Models/UsesCustomFieldsTraitTest.php, new Query Count group:

  • select count while saving 10 fields equals the count for 4 fields.
  • saving null clears every value and keeps the rows.
  • with lazy loading prevented, a saved listener can read the value's field options. It fails on 301b3b79 with the lazy-load violation and passes on the base 957508e9.

Checked

On the base commit 957508e9 the count test failed: Failed asserting that 21 is identical to 9. (select queries for 10 vs 4 fields).

At bcdc2bfa: UsesCustomFieldsTraitTest 22 passed; pint --test, rector --dry-run, phpstan analyse clean; pest --type-coverage --min=100 100%.

Inside Relaticle (v3.18.4 installed, this trait copied over the vendor file, then restored):

  • Task PATCH through the REST API: 51 queries at 4 fields and 81 at 10 before; 44 and 62 after. Custom-field selects stay at 11 and value selects at 5 for both sizes. The remaining growth is the per-field inserts for new rows.
  • Relaticle feature tests, all passing: Chat 2422, Filament 1991, MCP 922, REST API 666, ImportWizard 552 (1 skipped), CRM 291, ActivityLog 110, Models 10, Observers 9.

Not checked

  • Multi-tenancy with an explicit $tenant argument that differs from the scoped tenant is covered only by the existing suite, not a new test.
  • The php-code-styling check fails for a reason outside this PR: the action's composer:latest image no longer has mbstring, so Composer resolves Pint v0.1.7 (the Nov 13 run got v1.32.3), which crashes on mb_strimwidth. pint --test with the locked Pint passes locally.

Copilot AI balanced review requested due to automatic review settings November 20, 2026 15:48

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@ManukMinasyan
ManukMinasyan added this pull request to the merge queue Nov 20, 2026
Merged via the queue into 3.x with commit 7550815 Nov 20, 2026
6 of 7 checks passed
@ManukMinasyan
ManukMinasyan deleted the fix/save-values-without-per-field-queries branch November 20, 2026 19:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants