Laravel:模型之间的关系

时间:2015-08-11 20:12:41

标签: laravel laravel-4

我试图通过一个模型来获得另一个模型的数据。 该应用程序有几个型号:

产品:有许多部分(小型,中型)
部分:有许多PortionIngredients(ingredient_id - 100g OR 10pcs)
部分成分:有许多成分(培根,奶酪)
成分:有很多翻译(3种语言)

产品表

id
category_id
product_name

部分表

id
product_id
portion_name
portion_weight

PortionIngredients

id
portion_id
ingredient_id
amount

成分<​​/ P>

id
base_unit
transaction_unit
multiplier

我已经尝试在hasMany和belongsTo的模型中建立关系,但没有成功。我试图获得部分产品的所有成分。任何想法都表示赞赏。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果模型之间的关系设置正确,则类似于:

// models/Product.php
class Product extends Model
{
    public portions() {
        return $this->hasMany("Portion");
    }
}

// models/Portion.php
class Portion extends Model
{
    public product() {
        return $this->belongsTo("Product");
    }
    public ingredients() {
        return $this->belongsToMany("Ingredient");
    }
}

// models/Ingredient.php
class Ingredient extends Model
{
    public portions() {
        return $this->belongsToMany("Portion");
    }
}

应该可以获取包含所有部分和部分成分的产品:

$product = Product::with("portions.ingredients")->find($id)

检查Laravel文档中的Nested Eager Loading

相关问题