Answer the question
In order to leave comments, you need to log in
How to cache Eloquent model properties?
Good afternoon.
There is a model, it has a hasMany connection and there are several getters to get the number of connections.
Conceived simple example:
class Group extends Model
{
.....
public function Users()
{
return $this->hasMany(User::class);
}
/**
* Геттер количества активных пользователей
*/
public function getUsersActiveCountAttribute()
{
return $this->Users()->where('status', '=', 'active')->count();
}
/**
* Геттер количества заблокированных пользователей
*/
public function getUsersBlockedCountAttribute()
{
return $this->Users()->where('status', '=', 'blocked')->count();
}
}
@if($City->users_active_count > 0)
Количество активных: {{$City->users_active_count}}
@endif
@if($City->users_blocked_count > 0)
Количество заблокированных: {{$City->users_blocked_count}}
@endif
Answer the question
In order to leave comments, you need to log in
you solve your problem incorrectly and do not read the docs - this is your worst mistake
. You can optimize the code and queries in two ways
. First:
for getters, get information from the collection, not from the database
public function getUsersActiveCountAttribute()
{
return $this->Users->where('status', '=', 'active')->count();
}
public function UsersActive()
{
return $this->hasMany(User::class)->where('status', '=', 'active');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question