DominikN.
DominikN.

Reputation: 1255

Laravel Eloquent - model relationship with pivot table

I can't really find a relationship solution for these models.

  1. Bus has multiple destinations
  2. Destination has multiple buses
  3. Term has one bus and one destination

Bus

Destination

Term


If bus had only one destination then I have this and I think it should work.

BUS MODEL

public function destinations()
{
    return $this->belongsToMany('App\Destination');
}

public function terms()
{
    return $this->hasManyThrough('App\Term', 'App\Destination');
}

DESTINATION MODEL

public function boats()
{
    return $this->belongsToMany('App\Boat');
}

public function terms()
{
  return $this->hasMany('App\Term');
}

TERM MODEL

public function destination()
{
  return $this->belongsTo('WBZ\Destination');
}

What I want to be able to achieve:

Bus::find(1)->destinations()->get();
Bus::find(1)->terms()->get();

Upvotes: 0

Views: 61

Answers (1)

Gabrielle-M
Gabrielle-M

Reputation: 1077

BUS MODEL.

public function destinations()
{
return $this->belongsToMany('App\Destination');
}

public function term()
{
return $this->hasOne('App\Term');
}

DESTINATION MODEL

public function term()
{
return $this->hasOne('App\Term');
}

public function buses()
{
return $this->belongsToMany('App\Bus');
}

Term Model.

public function destination()
{
 return $this->belongsTo('App\Destination');
}
public function bus()
{
 return $this->belongsTo('App\Bus');
}

Upvotes: 1

Related Questions