Laravel:格式化模板中数据透视表的数据

时间:2017-04-09 10:02:08

标签: laravel laravel-5 pivot laravel-5.3

在模板中,我想显示如下产品规格:

模型
品牌:华硕
接口
接口:PCI Express 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一次,然后显示该类型下的所有属性和值。

这是数据透视表的结构:

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

        $table->increments('id');
        $table->integer('product_id')->unsigned()->index();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->integer('specification_id')->unsigned()->index();
        $table->foreign('specification_id')->references('id')->on('specifications')->onDelete('cascade');
        $table->string('attribute');
        $table->string('value');
    });
}

我怎么能实现这个目标?我应该改变我的表结构吗?

1 个答案:

答案 0 :(得分: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方法。

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