Laravel Eloquent - Order users relationship by a method on the user model -
i'm working on api endpoint laravel spark.
this endpoint returns given team along users.
// in app\team public function users() { return $this->belongstomany( 'app\user', 'team_users', 'team_id', 'user_id' )->withpivot('role'); }
however, wish order users method on user model.
on app\user model have method:
public function currentqueuelength() { returns integer based upon users current appointments, }
is there way can return users relationship order users result of method?
if add current_queue_length
attribute user
model, can order attribute.
you can add attribute adding $appends
array , creating accessor:
class user extends model { protected $appends = ['currentqueuelength']; public function getcurrentqueuelengthattribute() { return $this->currentqueuelength(); } }
credit question: add custom attribute laravel / eloquent model on load?
then in team
can add method so:
class team extends model { public function users() { return $this->belongstomany( 'app\user', 'team_users', 'team_id', 'user_id' )->withpivot('role'); } public function usersbycurrentqueuelength() { return $this->users->orderby('current_queue_length'); } }
as mentioned in comment, issue approach sounds currentqueuelength()
costly operation (based on comment) ideally, conditionally, however, i'm unsure how that! may want reconsider approach implementing currentqueuelength()
may open more options way structure query.
Comments
Post a Comment