-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
loadCount
Incorrectly Triggers retrieved
Event for Parent Model
#51276
Comments
Thank you for reporting this issue! As Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub. If possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team. Thank you! |
There is a workaround for this issue that involves disabling events for the model, but I'm not sure if it's the right approach:
/**
* Load a set of aggregations over relationship's column onto the collection.
*
* @param array<array-key, (callable(\Illuminate\Database\Eloquent\Builder): mixed)|string>|string $relations
* @param string $column
* @param string|null $function
* @return $this
*/
public function loadAggregate($relations, $column, $function = null)
{
if ($this->isEmpty()) {
return $this;
}
$firstItem = $this->first();
return $firstItem::withoutEvents(function() use ($relations, $column, $function, $firstItem) {
$models = $firstItem->newModelQuery()
->whereKey($this->modelKeys())
->select($this->first()->getKeyName())
->withAggregate($relations, $column, $function)
->get()
->keyBy($this->first()->getKeyName());
$attributes = Arr::except(
array_keys($models->first()->getAttributes()),
$models->first()->getKeyName()
);
$this->each(function ($model) use ($models, $attributes) {
$extraAttributes = Arr::only($models->get($model->getKey())->getAttributes(), $attributes);
$model->forceFill($extraAttributes)
->syncOriginalAttributes($attributes)
->mergeCasts($models->get($model->getKey())->getCasts());
});
return $this;
});
} |
As Taylor indicated on the related PR, this is expected as an actual query is executed. |
Laravel Version
11.6.0
PHP Version
8.2.4
Database Driver & Version
mysql
Description
I have observed an unexpected behavior with the
loadCount
method. TheloadCount
method is intended to load the count of related models without firing theretrieved
event on the parent model, similar to howwithCount
operates. However, it appears to be triggering theretrieved
event for the parent model with invalid data. The following is the log for theretrieved
event for Post and Comment model:which triggers from this route:
the
Post
modelretrieved
event handler:Steps To Reproduce
tinker
and the following snippet:storage/logs/laravel.log
file.The text was updated successfully, but these errors were encountered: