枢轴模型中的Laravel关系

时间:2017-02-01 08:35:00

标签: php mysql laravel-5.2

我有三个表,其中一个是数据透视表(和数据透视模型),并尝试在数据透视模型中创建belongsTo关系(数据透视表中的外键),这样我就可以从其他表中获取相关名称(具有主表)键)。我想做的是通过以下图片说明:
枢轴表是:
enter image description here 其他表是:
enter image description here

它是枢轴模型:

class MproductIngredient extends Model {

public function qtyType() {
    return $this->belongsTo('App\TIngredientType','priQuantityTypeNo');
}

}
如何从其他表中获取相关名称(有主键)。

我的代码是:

@foreach($prd->ingredients a $ingredient)
     "{!! $ingredient->pivot->priQuantityTypeNo !!}"
     @endforeach

1 个答案:

答案 0 :(得分:0)

请根据我的理解描述您可以在下方建立关系

  

对于belongsstoMany

    public function qtyTypes()
    {
        return $this->belongsToMany('App\TIngredientType', 'pivot_table_name', 
          'main_table_id', 'TIngredientType_id');
    }
  

for hasOne

public function qtyType()
    {
        return $this->hasOne('App\TIngredientType');
    }
相关问题