Closed Jarvvski closed 6 years ago
When you use $model->sortable()
... you are using a local scope. So if you find out how to do it with your grown scope let me know.
Could you also post an example / link so I know whats append-able attribute about?
Sure.
So Let's assume I have a character
model which has a starting_xp
value. This character
can have multiple record
entries, which each have an xp
value.
To calculate the character
experience, we do a sum of all their record
experience
values, and add that to the character
default experience
.
It's never stored in a database, because it's always dynamic.
Here's the code snippet I am using in my own project (related to the above) trimed down to the relevant parts:
class character extends Model {
protected $appends = [
'experience'
];
public function records()
{
// using means a pivot table on character_id - record_id
return $this->belongsToMany('App\Models\ExperienceRecord')
->using('App\Models\CharacterExperienceRecord');
}
public function getExperienceAttribute()
{
// set a starting counter
$experience = 0;
// loop through records and add to counter
foreach ($this->records as $record) {
$experience = $experience + $record->ammount;
}
// return counter + starting_exp property (in db)
return $experience + $this->starting_experience;
}
}
Hopefully that's not too long for you, and makes sense!
Thank you though otherwise, for a really good package. For stored values, it works perfectly
Oh yea it makes sense, so you are using accessor to calculate the experience
.
I think you may invest some time in taking a look at overriding sortable, so you write your own logic of sorting and $direction
is provided for you.
So I imagine you can do some raw sql magic + use "aliasing".
Ok then, thanks @Kyslik.
I'll check those out, and see what turns up.
If I create a solution, I'll post it back here for others to use later
@Jarvvski any success? :crossed_fingers:
No, not yet sadly @Kyslik
I'm currently in the states, so I don't have much time to work on it. Need to iron out a search implimentation first
What's the best way to deal with appendable attributes in models? So essentially, computed properties that aren't stored natively in the database.
I'm guesing there isn't an easy work around for this