Latest

Thursday, July 13, 2017

Order by parent models value in eager loaded relation - Laravel

Asked by: Pedro


I have a Team model and User model with a many to many relationship. A team can have many users and a user can have many teams.

A Team also has an owner which is set as owner_id on the team row in the DB.

When I return members of the Team I want to have the owner listed first and then ordered by name. I believe there is an orderByRaw function but not 100% sure how to get this working:

public function getAllTeams() {
    return Team::with(['user' => function($query){
                $query->orderByRaw(DB::raw("id = team.owner_id"));
            }])->get();

}

Team Model

/**
 * Get the Users for the team
 */
public function users()
{
    return $this->belongsToMany('App\Models\User');
}

/**
 * Get Team owner
 */
public function owner()
{
    return $this->belongsTo('App\Models\User', 'owner_id')->first();
}

User Model

/**
 * Get One Team for the user
 */
public function team()
{
    return $this->belongsToMany('App\Models\Team')->first();
}

teams Table

  • id
  • name
  • owner_id

team_user table

  • user_id
  • team_id

Any help would be appreciated!



Source

No comments:

Post a Comment

Adbox