Level 26
I think in this scenario it'd be best to create a model for the pivot table:
class RecipeIngredient extends Model {
public function product() {
return $this->belongsTo(Product::class);
}
public function measurementUnit() {
return $this->belongsTo(MeasurementUnit::class);
}
}
class Recipe extends Model {
public function ingredients() {
return $this->hasMany(RecipeIngredient::class);
}
}
...
// Referencing single recipe ingredient
$ingredient->product->title;
$ingredient->measurement_unit->title;
Or if you wanted to reference them exactly as you describe above:
class Recipe extends Model {
public function ingredients() {
return $this->hasMany(RecipeIngredient::class)
->join('products', 'recipe_ingedients.product_id', 'products.id')
->join('measurement_units', 'recipe_ingredients.measurement_unit_id', 'measurement_units.id')
->select('recipe_ingredients.*', DB::raw('products.title as product_title'), DB::raw('measurement_units.title as measurement_unit_title'));
}
}
1 like