Laravel:在模板中格式化来自数据透视表 table 的数据

Laravel: Formatting data from pivot table in template

在模板中我想像这样显示产品规格:

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

这是枢轴的结构 table:

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

我怎样才能做到这一点?我应该更改我的 table 结构吗?

我认为实现此目的的最佳方法是使用一些 post 数据库处理。

取下面的代码。

// 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 或实际模型,但这可以很容易地适应它。您还可以对 Collection class.

使用 each 方法

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