My table structure is like this:
id user_id gift
1 1 1000
but now I want to move the gift
to another table since the gift can be given to the users more than once in different dates. I have used $user->gift
in many places in my project and I don't want to change the code. So I want to create a method in User
model called getGiftAttribute
. Inside this method I'm going to have the sum of the gifts. But now the problem is that each time that $user->gift
is called in my code it queries the database, but I want it to be called once. As previously if I used $user->gift
, it would query only once. So how can I get the sum of gift
which is in another table without querying more than once?
CodePudding user response:
If you really don't want to change your code at all and get the sum of gifts at multiple places with only one query, you could do something like this:
class User extends Models {
protected $sumGifts = null;
// [...]
public function getGiftAttribute()
{
if($this->sumGifts == null){
$this->sumGift = $this->gifts()->sum('gift');
// or whatever you use to retrieve the sum of all gifts
}
return $this->sumGifts;
}
}
Doing so, you are storing the sum of all gifts inside a property of your User model and therefore the query will be executed only once, when you first use $user->gift
. All subsequent calls to $user->gift
will return the sum previously stored in the sumGifts
property.
It will work, however, I think a better approach would be to wisely use relationships and eagerloading.
CodePudding user response:
If you add the gifts
to the user as a relationship, then laravel should automatically only query the gifts table once per user.
If you want to get the gifts for multiple users and only want to access the gifts
table once, then you can use eager loading.
For example, you could write ->with('gifts')
in your users query.