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

Laravel:在模板中格式化数据透视表中的数据,laravel,laravel-5,pivot,laravel-5.3,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 . ': ' . $specif

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

型号
品牌:华硕
接口
接口:PCI Express 3.0

我尝试在此foreach中添加另一个循环,但出现错误:

foreach ($product->specifications as $specification) {
    echo $specification->name . '</br>';
    echo $specification->pivot->attribute . ': ' . $specification->pivot->value . '</br>';
}
我只需要显示一次
$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');
    });
}

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

我认为实现这一点的最好方法是进行一些后期数据库处理

以下面的代码为例

// 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
方法

不管怎样,希望这有帮助

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