Skip to content

Commit 9fde5ff

Browse files
committed
fix n+1
1 parent 61cc52c commit 9fde5ff

File tree

3 files changed

+7
-11
lines changed

3 files changed

+7
-11
lines changed

src/Fields/Meta.php

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ public function __construct(string $label, Closure|string|null $modelAttribute =
3333
->one()
3434
->ofMany(
3535
[$related->getCreatedAtColumn() => 'MAX'],
36-
fn (Builder $query): Builder => $query->where($related->qualifyColumn('key'), $this->getModelAttribute()),
36+
function (Builder $query) use ($related): Builder {
37+
return $query->where($related->qualifyColumn('key'), $this->getModelAttribute());
38+
},
3739
'metaData'
3840
)
3941
->withDefault(['key' => $this->getModelAttribute()]);
@@ -93,17 +95,11 @@ public function getValue(Model $model): mixed
9395
{
9496
$name = $this->getRelationName();
9597

96-
if (
97-
$this->relation instanceof Closure
98+
if ($this->relation instanceof Closure
9899
&& $model->relationLoaded('metaData')
99100
&& ! $model->relationLoaded($name)
100-
&& ! is_null(
101-
$value = $model->getRelation('metaData')
102-
->sortByDesc('created_at')
103-
->firstWhere('key', $this->getModelAttribute())
104-
)
105101
) {
106-
$model->setRelation($name, $value);
102+
$model->setRelation($name, $model->metaValue($this->getModelAttribute()));
107103
}
108104

109105
return parent::getValue($model);

src/Root.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class Root
2727
*
2828
* @var string
2929
*/
30-
public const string VERSION = '2.7.8';
30+
public const string VERSION = '2.7.9';
3131

3232
/**
3333
* The registered booting callbacks.

src/Traits/HasMetaData.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,6 @@ public function metaData(): MorphMany
2222
*/
2323
public function metaValue(string $key, mixed $default = null): mixed
2424
{
25-
return $this->metaData->firstWhere('key', $key)?->value ?: $default;
25+
return $this->metaData->sortByDesc('created_at')->firstWhere('key', $key)?->value ?: $default;
2626
}
2727
}

0 commit comments

Comments
 (0)