/** * @inheritdoc */ public function run() { if ($this->model === null) { throw new InvalidConfigException("Model should be set for WarehousesRemains widget"); } $state = $this->model->getWarehousesState(); $activeWarehousesIds = Warehouse::activeWarehousesIds(); $remains = []; foreach ($state as $remain) { $remains[$remain->warehouse_id] = $remain; if (($key = array_search($remain->warehouse_id, $activeWarehousesIds)) !== false) { unset($activeWarehousesIds[$key]); } } // if we have new warehouses that not represented in warehouses state if (count($activeWarehousesIds) > 0) { foreach ($activeWarehousesIds as $id) { // create new record with default values $remain = new WarehouseProduct(); $remain->warehouse_id = $id; $remain->product_id = $this->model->id; $remain->save(); // add to remains $remains[$remain->warehouse_id] = $remain; } TagDependency::invalidate(Yii::$app->cache, ActiveRecordHelper::getObjectTag($this->model->className(), $this->model->id)); } return $this->render('warehouses-remains', ['model' => $this->model, 'remains' => $remains]); }
/** * @param null $id * @param bool $create * @return null|\app\models\WarehouseProduct */ public static function findByProductId($id = null, $create = true) { if (null === $id) { return null; } if (null !== ($model = static::findOne(['product_id' => $id]))) { return $model; } if (true === $create) { $warehouses = Warehouse::activeWarehousesIds(); if (!empty($warehouses)) { $model = new static(); $model->warehouse_id = $warehouses[0]; $model->product_id = $id; $model->in_warehouse = 0; $model->save(); return $model; } } return null; }
/** * Returns remains of this product in all active warehouses. * Note that if warehouse was added after product edit - it will not be shown here. * @return WarehouseProduct[] */ public function getWarehousesState() { if ($this->activeWarehousesState === null) { $this->activeWarehousesState = WarehouseProduct::getDb()->cache(function ($db) { return WarehouseProduct::find()->where(['in', 'warehouse_id', Warehouse::activeWarehousesIds()])->andWhere('product_id=:product_id', [':product_id' => $this->id])->with('warehouse')->all(); }, 86400, new TagDependency(['tags' => [ActiveRecordHelper::getObjectTag($this->className(), $this->id)]])); } return $this->activeWarehousesState; }