lundi 29 mai 2017

Laravel 5 Eloquent Relationship with Pivot Table

I have three tables:

  • Users (id, name, email)
  • Competitions (id, name, user_id)
  • Competitors (id, user_id, competition_id)

I wish to set up an eloquent relationship between the three tables. The competitors table is a pivot table for the other two tables. So far I have the following code, which allows me to list all competitions a user owns and allows me to add a competitor to a competition. However, I am struggling to get user details of all competitors in competition

class User {
  public function competitions() {
    return $this->hasMany(Competition::class);
  }
}

class Competition {
  public function join($user_id = 0) {
    $user_id = ($user_id == 0) ? \Auth::id() : (int)$user_id;

    $competitor = new Competitor(['user_id' => $user_id]);

    $this->competitors()->save($competitor);
  }

  public function users() {
    return $this->belongsTo(User::class);
  }

  public function competitors()
  {
    return $this->hasMany(Competitor::class);
  }
}

class Competitor {

}

What do I need to add to the relationships to return all competitors in a competition. Ideally I want to be able to do something likes this:

foreach($competition->competitors as $competitor) {
  echo $competitor->name.' '.$competitor->email; // etc
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2ryPYvT
via IFTTT

Aucun commentaire:

Enregistrer un commentaire