【发布时间】:2018-07-01 18:25:44
【问题描述】:
如何减少laravel的库存数量?
在我的产品表中,我有 stock 列,我在其中设置了我拥有的商品数量,我想在 2 种情况下减少它:
1- 何时添加到订单表(而不是产品在用户购物车中)
2-当订单状态未取消时(如果订单状态变为已取消库存增加回来)
PS:目前我没有这件事的代码,所以我没有分享 任何代码,我正在寻找有关如何完成它的想法。基于此,我会 制作函数并在这里分享完成。
订单的JSON
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\":1,\"attributes\":[{\"attr\":{\"label\":\"Gray\",\"price\":\"7000.00\"}}],\"conditions\":[]},{\"id\":27,\"name\":\"new product\",\"price\":7246,\"quantity\":2,\"attributes\":[],\"conditions\":[]}]"
更新
基于@btl 的回答,我在order 模型中添加了以下代码:
protected static function boot()
{
parent::boot();
$productIdsAndQuantities = $this->products->map(function ($product) {
return [$product->id => $product->quantity];
});
static::updating(function (Order $order) {
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
我认为这段代码需要在$productIdsAndQuantities 和$product->update(['stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)]); 部分修复才能使用它。
目前,当我尝试将购物车详细信息添加到订单表时,出现以下错误
不在对象上下文中使用 $this
更新 2
我将代码更改为:
protected static function boot()
{
parent::boot();
static::updating(function (Order $order) {
$productIdsAndQuantities = $order->product_name->map(function ($product) {
return [$product->id => $product->quantity];
});
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
现在我的订单将被下达,但库存列没有任何变化。
有什么想法吗?
【问题讨论】:
-
您应该创建另一个具有关联 order_id 和 product_id 的表名 stock 然后添加股票上涨或下跌的详细信息。
-
@SagarGautam 那么我的产品表中的库存列呢?
-
股票列有初始值吗?
-
由于只是增加/减少库存值可能会在以后引起问题,并且您必须跟踪库存值列的整体变化,我认为您需要另一个表。
-
这是因为你还没有开始编码LOL,我会尝试添加一些代码。
标签: laravel