我正在试图在Laravel上购物,但我仍然是一个学习者。
在购物车中,我正在尝试打印购物车中存在的产品的详细信息及其数量。
$prod
中显示购物车的几种产品的详细信息,而$cart
中显示数量。我正在运行foreach
以访问购物车的每种产品及其数量。
以一种解释性的方式,我正在尝试这样做:
@foreach( $prod as $p )
<td>Quantity = {{ $cart[ "product_id" == $p->id]->quantity }}<td>
@endforeach
我正在尝试将我正在打印的详细信息$p->id
与$cart
中的数量进行匹配,因为$cart
在表的product_id
属性下具有它。
对不起,如果我无法以正确的方式解释该问题。
谢谢。
此解决方案假定您正在使用Eloquent模型,如果不是,请使用。在Product.php
模型上,定义关系。
class Product extends Model {
public function cart()
{
// Laravel automatically know to look in carts table for an product_id column
return $this->belongsTo(Cart::class);
}
}
现在您有一个购物车的关联方法,如果要保存它,这很有用。只需将其从数据库中加载,如果您访问$product->cart
,它将自动获取Cart.php
模型。这样您就可以简单地编写。
@foreach( $prod as $p )
<td>Quantity = {{ $p->cart->quantity }}<td>
@endforeach