2017-04-09 61 views
0

在模板我想顯示的產品規格如下:Laravel:從數據透視表模板格式數據

型號
品牌:華碩
接口
接口:PCI高速3.0
...

我試圖在這個foreach中添加另一個循環,但有錯誤:

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

目前這款輸出:

Model 
Brand: Asus 
Interface 
Interface: PCI Express 3.0 
Chipset 
Chipset Manufacturer: AMD 
Chipset 
GPU: Radeon RX 470 
Chipset 
Core Clock: 1270 MHz in OC mode 
Memory 
Effective Memory Clock: 6600 MHz 
Memory 
Memory Size: 4GB 
Memory 
Memory Interface: 256-Bit 
Memory 
Memory Type: GDDR5 

我需要顯示$specification->name只有一次,那麼該類型下的所有屬性和值。

這是透視表的結構:

​​

我怎麼能做到這一點?我應該改變我的表格結構嗎?

回答

1

我認爲實現這一目標的最好方法是使用一些後期數據庫處理。

取下面的代碼。

// Create a new collection 
$specifications = new Collection; 

// Loop through specifications 
foreach($product->specifications as $specification) { 
    if (! $specifications->has($specification->name)) { 
     // This is the first specification of this name 
     $currentSpecs = new Collection; 
    } else { 
     // Other specifications have been entered 
     $currentSpecs = $specifications->get($specification->name); 
    } 

    // Now we add the current spec to the list and set it on the main collection 
    // Using the core name as the key 
    $currentSpecs->put($specification->pivot->attribute, $specification->pivot->value); 
    $specifications->put($specification->name, $currentSpecs); 
} 

現在在您的模板中,您可以執行以下操作。

foreach($specifications as $name => $attributes) { 
    echo $name; 
    foreach($attributes as $attribute => $value) { 
     echo $attribute .': '. $value; 
    } 
} 

很顯然,我認爲你不需要任何的ID或實際的車型,但是這可能很容易地適應與合作。您也可以使用each方法來獲得Collection類。

無論如何,希望這有助於。