2017-04-09 124 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>'; 
} 
相關問題