Laravel 5.x,其中有多对多的带有额外的枢轴列

时间:2018-05-15 21:00:47

标签: php laravel eloquent many-to-many

我在Recipes和Ingredients之间设置了多对多数据透视表。对于特定的成分,我想要一个Recipies列表

$ingredientID = 99;

$recipies = Recipe::whereHas('ingredients', function ($q) use ($ingredientID) {
    $q->where('id', '=', $ingredientID);
})->get();

这很有效。但在我的情况下,数据透视表中有一个额外的列用于“描述”。例如,特定的“饼干”食谱和“鸡蛋”成分连接可能有描述:“确保鸡蛋对于这个食谱来说真的很新鲜”。

那么如何使用此查询返回额外的数据透视表列?我已经尝试进入模型文件并添加“withPivot”调用,如下所示:

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

但这不起作用。知道如何威胁我的whereHas查询咳嗽这个额外的数据透视表列吗?

1 个答案:

答案 0 :(得分:0)

要访问description透视列,您可以执行以下操作:

$recipies->first()->ingredients->first()->pivot->description;
相关问题