Laravel:如何从此数据透视表中获取数据?

时间:2017-04-09 09:01:01

标签: php laravel laravel-5 pivot-table laravel-5.3

已解决:在下面发布的答案

如何从此数据透视表和规格表中获取值?

我想在以下模板中显示:

-Model(规范表中的名称)

- 品牌(属性表格数据透视表):example1(数据透视表中的值)

- 模型(属性表格数据透视表):example123(数据透视表中的值) ...

在ProductController中,我尝试返回类似$product = Product::with('specifications')->first();的内容,但之后我只能从规格表中获取数据,如果我尝试$product = Product::with('product_specification')->first();,我会收到错误Call to undefined relationship [product_specification] on model [App\Product].

数据透视表:

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

规格表:

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

        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}

产品型号:

public function specifications() 
{
    return $this->belongsToMany(Specification::class, 'product_specification');
}

1 个答案:

答案 0 :(得分:3)

我必须将withPivot()添加到我的产品型号

public function specifications() {
    return $this->belongsToMany(Specification::class, 'product_specification')->withPivot('attribute', 'value');
}

然后在模板中:

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