【发布时间】:2020-08-02 20:10:09
【问题描述】:
我试图在 Laravel 中建立一个电子商务网站,但我收到了错误消息 “例外 Eloquent 构建器实例上不存在属性 [product_quantity]。” 当我尝试更新数据库中的产品数量时。
基本上,我想做的是,如果用户尝试添加购物车中已经存在的产品,则数量会增加 1,并且产品总价格也会相应更改。为此,我首先使用
检查数据库中的现有条目$findProduct = StoreCart::where('product_id', $product->id);
“StoreCart”是我存储购物车数据的模型名称。然后在查找查询之后我所做的是
if($findProduct) {
// product is already in DB, set new quantity
$newQuantity = $findProduct->product_quantity + $getQuantity;
$newProductTotal = $findProduct->product_price * $newQuantity;
// update the exsisting product
$findProduct->update([
'product_quantity' => $newQuantity,
'product_total' => $newProductTotal,
]);
} else {
// create new field and store it in db
StoreCart::create([
'user_id' => Auth::id(),
'product_id' => $product->id,
'product_name' => $product->name,
'product_price' => $amount,
'product_quantity' => $getQuantity,
'product_total' => $productTotal,
]);
}
当我尝试运行它时,会弹出上述错误,说 [product_quantity] 在 Eloquent 构建器实例上不存在。 这有什么问题?
【问题讨论】:
-
检查我的答案。