Php 拉威尔:我如何从这个数据透视表中获取数据?
已解决:答案张贴在下面 如何从该透视和规格表中获取值 我想在如下模板中显示: -型号(规格表中的名称) --品牌(属性表透视表):示例1(透视表中的值) --模型(属性表单透视表):示例123(透视表中的值)Php 拉威尔:我如何从这个数据透视表中获取数据?,php,laravel,laravel-5,pivot-table,laravel-5.3,Php,Laravel,Laravel 5,Pivot Table,Laravel 5.3,已解决:答案张贴在下面 如何从该透视和规格表中获取值 我想在如下模板中显示: -型号(规格表中的名称) --品牌(属性表透视表):示例1(透视表中的值) --模型(属性表单透视表):示例123(透视表中的值) 在ProductController中,我尝试返回如下内容:$product=product::with('specifications')->first(),但我只能从规格表中获取数据,如果我尝试使用('product_specification')->first()我收到错误调用模
在ProductController中,我尝试返回如下内容:
$product=product::with('specifications')->first()代码>,但我只能从规格表中获取数据,如果我尝试使用('product_specification')->first()代码>我收到错误调用模型[App\product]上未定义的关系[product\u specification]。
数据透视表:
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');
}
我必须将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>';
}
foreach($product->specification as$specification){
回显“名称:”。$specification->name。“属性:”。$specification->pivot->attribute。“值”。$specification->pivot->value。“”;
}
您对做了什么?如何从该透视和规格表中获取值?
@rudolph@AndyK在ProductController中,我尝试返回如下内容:$product=product::with('specifications')->first()代码>,但我只能从规格表中获取数据,如果我尝试使用('product_specification')->first()代码>我得到错误调用模型[App\product]上未定义的关系[product\u specification]。
将其放入问题中。我们必须知道@鲁道夫