Repository navigation
Replies: 1 comment
|
The accessor fires because To make it genuinely lazy you have to construct the object yourself, so what gets stored is the closure rather than the value: public static function fromModel(User $user): self
{
return new self(
$user->id,
$user->name,
Lazy::create(fn () => $user->avatarUrl),
);
}Now nothing touches If what you actually want is "give me the URL when the relation is already loaded, but never go and fetch it", there's a dedicated helper for that: Lazy::whenLoaded('avatar', $user, fn () => $user->avatar?->url),That one is skipped entirely when the relation isn't loaded, so it can't trigger a query even if someone does include it — which makes it the safer default when these objects get built in a loop. |
Uh oh!
There was an error while loading. Please reload this page.
Let’s start by defining some classes:
Now, the following code will silently auto-load the
avatarrelation:This happens because
avatarUrlis not a real attribute—it’s computed from a model relation.Now, after adding the
#[AutoLazy]attribute,avatarUrlbecomes lazy as expected.However, it still triggers an automatic relationship load, occurring in
NormalizedModel::fetchNewProperty.So, how can we make
avatarUrltruly lazy (i.e., avoid querying the relation unless it’s actually accessed)?I’ve thought of one solution: use a custom
frommethod.Amazing! It works exactly as expected.
But this raises another issue: good practice in database querying says we should only select the fields we need—never use wildcards.
So let’s modify the query:
Now
$useronly has theid, yet it can still access theavatarUrlthrough thehasOnerelation.However, this code doesn’t behave well:
namefield doesn’t exist.namebecomesnull, which causes a type error sincenameis non-nullable.So should we just make the field nullable? That would avoid the error, and since we used
only,namewon’t appear in the final output anyway.I also came up with another approach:
Then:
This seems to reduce boilerplate nicely.
Or?
So—am I missing something here? Is there a better approach? Thanks.
Relation: #1071 #378
All reactions