控制者
public function showSpecificProduct($name)
{
$product = Product::with('subproducts')->where('name', $name)->first();
return view('products.single')->with('products',$product);
}
视图
{{ $product->name }} // shows the name of the mainproduct no need for a foreach
要显示子产品,您必须进行foreach循环(如果它们很多)
@foreach (($product->subproducts as $subproduct)
{{ $subproduct->name}}
@endforeach
为此,您必须先在模型和迁移中设置关系
像这样
1迁移
产品迁移
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->text('name');
$table->timestamps();
});
}
子产品迁移
public function up()
{
Schema::create('subproducts', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('subproducts');
$table->text('name');
$table->timestamps();
});
}
如果您没有正确的外键设置,请刷新您的迁移
2种型号
将此添加到您的产品模型
编辑
public function subproducts() {
return $this->hasMany('App\Subproduct', 'product_id'); // you can this
}
副产品型号
public function product() { // i made a mistake here
return $this->belongsTo('App\Product');
}
现在随时使用雄辩的ORM.