Skip to content

Instantly share code, notes, and snippets.

@j-dexx
Created February 23, 2018 10:30
Show Gist options
  • Save j-dexx/14df25eb7a4b4d0b46ce7f993f74f1a9 to your computer and use it in GitHub Desktop.
Save j-dexx/14df25eb7a4b4d0b46ce7f993f74f1a9 to your computer and use it in GitHub Desktop.
Has many through belongs to
class Ingredient
{
public function section()
{
return $this->belongsTo(Section::class);
}
}
class Option
{
public function sections()
{
return $this->hasMany(Section::class);
}
}
class Recipe {
public function sections()
{
return $this->hasMany(Section::class);
}
public function ingredients()
{
// Default has many through
return $this->hasManyThrough(Ingredient::class, Section::class);
// is actually return $this->hasManyThrough(Ingredient::class, Section::class, 'recipe_id', 'section_id', 'id', 'id');
}
public function options()
{
// Has many through a belongs to relationship
// Reversing the keys allows the join to work correctly
return $this->hasManyThrough(Option::class, Section::class, 'recipe_id', 'id', 'id', 'option_id');
}
}
class Section {
public function ingredients()
{
return $this->hasMany(Ingredient::class);
}
public function option()
{
return $this->belongsTo(Option::class);
}
public function recipe()
{
return $this->belongsTo(Recipe::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment