2017-04-09 120 views
2

解决:回答下面贴Laravel:我如何从这个数据透视表中获取数据?

我怎样才能从这个支点和规格表中的值?

我想在像一个模板显示这些:

- 模型(名称从参数表)

- 品牌(属性形式枢轴表):示例1(从枢轴表值)

--model(属性形式枢轴表):example123(从枢轴表值) ...


在ProductController的我试图换货政... rning像这样$product = Product::with('specifications')->first();,但我可以从规格表中只得到数据,如果我尝试$product = Product::with('product_specification')->first();我得到错误Call to undefined relationship [product_specification] on model [App\Product].


透视表:

​​

规格表:

public function up() 
{ 
    Schema::create('specifications', function (Blueprint $table) { 
     $table->engine = 'InnoDB'; 

     $table->increments('id'); 
     $table->string('name')->unique(); 
     $table->timestamps(); 
    }); 
} 

产品型号:

public function specifications() 
{ 
    return $this->belongsToMany(Specification::class, 'product_specification'); 
} 
+0

你做了什么来'我怎样才能从这个支点和规格表中获取值?'@rudolph –

+0

@AndyK在ProductController中,我尝试返回类似这样的'$ product = Product :: with('specifications') - > first();',但是我只能从规格表中获取数据,如果我尝试'$ product = Product :: with('product_specification') - > first();'我得到错误'调用未定义的关系[product_spe cification]放在型号[App \ Product]上。' – Rudolph

+0

将它放在问题伴侣中。我们必须知道! @rudolph –

回答

2

我不得不withPivot()添加到我的产品型号

public function specifications() { 
    return $this->belongsToMany(Specification::class, 'product_specification')->withPivot('attribute', 'value'); 
} 

然后在模板:

foreach($product->specifications as $specification) { 
    echo 'name: ' . $specification->name . ' attribute: ' . $specification->pivot->attribute . ' value ' . $specification->pivot->value . '</br>'; 
} 
相关问题