A
A
Andrey Surzhikov2019-01-11 12:40:28
Laravel
Andrey Surzhikov, 2019-01-11 12:40:28

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();
}

}

I want to display the number of users in the blade, if it is not 0;
@if($City->users_active_count > 0)
Количество активных: {{$City->users_active_count}}
@endif

@if($City->users_blocked_count > 0)
Количество заблокированных: {{$City->users_blocked_count}}
@endif

It turns out that the query to the database is executed twice (when checking and when outputting). This is bad.
The question is how to make the most elegant option how to avoid this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin B., 2019-01-11
@Surzhikov

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();
}

Second:
Take data from the database after loading it
public function UsersActive()
{
  return $this->hasMany(User::class)->where('status', '=', 'active');
}

In the controller, do not forget to load this data
For the first For the second When you receive in the second way, then for each group you will have a property available. I advise you to first read the document thoughtfully and several times

A
Arman, 2019-01-11
@Arik

So by chance does not know how Blade?

@if(($t = $City->users_active_count) > 0)
Количество активных: {{$t}}
@endif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question