【问题标题】:Laravel: How do I get data from this pivot table?Laravel:我如何从这个数据透视表中获取数据?
【发布时间】:2017-09-04 10:05:05
【问题描述】:

已解决:答案贴在下面

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

我想在这样的模板中显示它:

-型号(规格表中的名称)

--品牌(属性形式透视表):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');
}

【问题讨论】:

  • 你对How can I get values from this pivot and specifications table?@rudolph做了什么
  • @AndyK 在 ProductController 中我尝试返回类似 $product = Product::with('specifications')->first(); 的内容,但是我只能从规格表中获取数据,如果我尝试 $product = Product::with('product_specification')->first(); 我会收到错误 Call to undefined relationship [product_specification] on model [App\Product].
  • 把它放在问题伙伴中。我们必须知道! @鲁道夫

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


【解决方案1】:

我必须将 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>';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2017-10-16
    相关资源
    最近更新 更多