2017-04-09 4 views
0

In Vorlage I Produktspezifikationen wie folgt angezeigt werden soll:Laravel: Formatierung von Daten aus Pivot-Tabelle in Vorlage

Modell
Marke: Asus
Schnittstelle
Schnittstelle: PCI Express 3.0
...

ich habe versucht, eine weitere Schleife in diesem foreach Hinzufügen, bekam aber Fehler:

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

Derzeit wird diese Ausgänge:

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 

Ich brauche $specification->name nur einmal angezeigt werden und dann alle Attribute und Werte unter diesem Typ.

Dies ist die Struktur der Pivot-Tabelle:

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'); 
    }); 
} 

Wie kann ich das erreichen? Soll ich meine Tabellenstruktur ändern?

Antwort

1

Ich denke, der beste Weg, um dies zu erreichen ist mit einigen Post-Datenbank-Verarbeitung.

Nehmen Sie den folgenden Code.

// 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); 
} 

Jetzt in Ihrer Vorlage können Sie Folgendes tun.

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

Offensichtlich habe ich davon ausgegangen, dass Sie eine der IDs oder aktuelle Modelle nicht brauchen, aber dies sehr leicht angepasst werden könnte, damit zu arbeiten. Sie können auch die each-Methode für die Klasse Collection verwenden.

Wie auch immer, hoffe das hilft.