Reputation: 24472
users
tablepets
tablebelongsToMany
.user_pets
with information regards a speicifc pet of an user.I get the user pets, including the pivot table information using $user->pets()
. the pets()
method in my User Model is:
public function pets()
{
$pets = $this->belongsToMany(Pet::Class, 'user_pets')->withPivot(
'id',
'position',
'level',
'exp'
)->orderBy('position','asc');
return $pets;
}
As you can see, every pet as level
and exp
fields. the exp required to get the next level is listed in my pet_exp
table:
ID | level | requiredExp
1 5 237
2 6 406
3 7 637
4 8 942
5 9 1326
6 10 1800
7 11 2369
$user->pets()
(the method above). I've been thinking for couple of hours and couldn't think of a way how to do it. Hopefully you can help me, Thanks!
Upvotes: 1
Views: 56
Reputation: 9146
Here's how I would do it:
In your Pet
model add a requiredexp
function:
function requiredexp() {
return DB::table('pet_exp')->where('level', $this->level)->value('requiredExp');
}
This should return the requiredExp for the level of the pet that you call the function on (i.e. $pet->requiredexp
)
EDIT:
You can also do it as an attribute:
function getRequiredexpAttribute($value) {
return DB::table('pet_exp')->where('level', $this->level)->value('requiredExp');
}
Upvotes: 1