2017-04-09 103 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类。

无论如何,希望这有助于。