php查询数据库的两个值,php-Laravel:Controller中有2个数据库查询,而第...

控制者

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值