[英]Laravel: How do I get data from this pivot table?
SOLVED : answer posted below 求助 :答案发布在下面
How can I get values from this pivot and specifications table? 如何从此数据透视表和规格表中获取值?
I want to display this in a template like: 我想在模板中显示这个:
-Model (name from specifications table) -Model(规格表中的名称)
--Brand (attribute form pivot table): example1 (value from pivot table) --Brand(属性表格数据透视表):example1(数据透视表中的值)
--Model (attribute form pivot table): example123 (value from pivot table) ... --Model(属性表格数据透视表):example123(数据透视表中的值)...
In ProductController I tried returning something like this $product = Product::with('specifications')->first();
在ProductController中,我尝试返回类似
$product = Product::with('specifications')->first();
, but then I can get only data from specifications table and if I try $product = Product::with('product_specification')->first();
,但是我只能从规格表中获取数据,如果我尝试
$product = Product::with('product_specification')->first();
I get error Call to undefined relationship [product_specification] on model [App\\Product].
我收到错误
Call to undefined relationship [product_specification] on model [App\\Product].
Pivot 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');
});
}
Specifications table: 规格表:
public function up()
{
Schema::create('specifications', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
Product model: 产品型号:
public function specifications()
{
return $this->belongsToMany(Specification::class, 'product_specification');
}
I had to add withPivot() to my Product model 我不得不将withPivot()添加到我的Product模型中
public function specifications() {
return $this->belongsToMany(Specification::class, 'product_specification')->withPivot('attribute', 'value');
}
And then in template: 然后在模板中:
foreach($product->specifications as $specification) {
echo 'name: ' . $specification->name . ' attribute: ' . $specification->pivot->attribute . ' value ' . $specification->pivot->value . '</br>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.