从桥表laravel中检索数据

时间:2017-06-03 03:59:42

标签: php laravel laravel-5.3

DB

我有问题要检索" 部分"表格中的数据" ingredient_recipe"。有没有办法获得" 部分"不使用Query Builder的数据?这是我在食谱模型中检索成分的代码。问题是我想从Recipe模型中检索部分值。

class Recipe extends Model
{
  public function ingredients(){
        return $this->belongsToMany('App\Ingredient');
  }
}

1 个答案:

答案 0 :(得分:0)

在您的关系中添加数据透视表列

public function ingredients()
{
    return $this->belongsToMany('App\Ingredient')->withPivot('portion');
}

然后像

一样访问它
$recipe = Recipe::find(1);

foreach ($recipe->ingredients as $ingredient) {
    echo $ingredient->pivot->portion;
}
相关问题