statamic / cms

The core Laravel CMS Composer package
https://statamic.com
Other
3.58k stars 489 forks source link

Asset Fieldtype performs multiple queries when templating using Colon Instead of tag pair #10296

Open DanielDarrenJones opened 3 weeks ago

DanielDarrenJones commented 3 weeks ago

Bug description

If you access a variable on an asset fieldtype directly using a colon like so:

{{ hero_image:url }}
{{ hero_image:alt }}

A query will be performed for each variable you access, this could potentially be reduced by implementing blink caching here, otherwise we could document this behaviour in the docs, let me know which you would prefer and I can submit a PR?

How to reproduce

Add a asset fieldtype with a limit of 1 to an entry, access the field in antlers like so:

{{ hero_image:url }}
{{ hero_image:alt }}

Each additional attribute you access will make an additional SQL query (I have only tested this on the eloquent driver).

Logs

No response

Environment

Environment
Application Name: Pelorus
Laravel Version: 10.48.12
PHP Version: 8.2.19
Composer Version: 2.7.7
Environment: local
Debug Mode: ENABLED
URL: localhost
Maintenance Mode: OFF

Cache
Config: NOT CACHED
Events: NOT CACHED
Routes: NOT CACHED
Views: CACHED

Drivers
Broadcasting: log
Cache: redis
Database: mysql
Logs: stack / single
Mail: log
Queue: redis
Session: redis

Statamic
Addons: 8
Sites: 8 (Travel (GB), Travel (US), Aviation (GB), and 5 more)
Stache Watcher: Disabled
Static Caching: Disabled
Version: 5.7.3 PRO

Statamic Addons
aryehraber/statamic-captcha: 1.11.0
doefom/currency-fieldtype: 1.4.0
gerttimmerman/statamic-zapier: 1.6
jacksleight/statamic-bard-texstyle: 3.2.2
ndx/statamic-bard-color-picker: 2.0.0
ryanmitchell/statamic-translation-manager: 2.0.0
statamic/eloquent-driver: 4.2.0
withcandour/aardvark-seo: 5.0.0

Statamic Eloquent Driver
Asset Containers: eloquent
Assets: eloquent
Blueprints: file
Collection Trees: file
Collections: file
Entries: file
Forms: file
Global Sets: file
Global Variables: file
Navigation Trees: file
Navigations: file
Revisions: file
Taxonomies: file
Terms: file
Tokens: file

Installation

Fresh statamic/statamic site via CLI

Additional details

No response

ryanmitchell commented 2 weeks ago

I noticed this pre-v5 but hoped the augmentation changes might avoid it. It feels to me that the results of augment() in the assets field type should be blinked, are there any downsides to that?

The same issue happens with other relationship field types (eg entries).

[edit] I think the issue is they return query builders, not a collection, so not sure how possible it would be to Blink them.

RobMaple commented 2 weeks ago

FWIW... as a workaround I've managed to cut down the number of asset queries by reassigning the asset field to a new variable before accessing properties. Seemingly when reassigned, the new varaible no longer queries when accessing properties. For example: `{{new_image_field = image_field}}

`