model() public static method

Returns the static model of the specified AR class.
public static model ( string $className = __CLASS__ ) : Product
$className string active record class name.
return Product Static model class
 public function loadModel($id)
 {
     if (($model = Product::model()->findByPk($id)) === null) {
         throw new CHttpException(404, 'Страница не найдена');
     }
     return $model;
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate($id)
 {
     if (!empty($id) && !Yii::app()->user->isGuest) {
         $customer_email = Yii::app()->user->name;
         $customerModel = Customer::model()->findByAttributes(array('customer_email' => $customer_email));
         $productId = $id;
         $productModel = Product::model()->findByPk($productId);
         $model = new Order();
         $model->order_product_id = $productModel->product_id;
         $model->order_customer_id = $customerModel->customer_id;
         $model->order_amount = $productModel->product_price + $productModel->product_shipping_price;
         if ($model->save()) {
             $attribuits = Order::model()->findByPk($model->order_id);
             $str = "Product Name:{$productModel->product_name}\r\n" . "Order Id:{$attribuits->order_id}\r\n" . "Order Product Id:{$attribuits->order_product_id}\r\n" . "Order Customer Id:{$attribuits->order_customer_id}\r\n" . "Total Amount With Shipping Charges:{$attribuits->order_amount}\r\n";
             $message = new YiiMailMessage();
             $message->subject = "Your order details";
             $message->setBody($str);
             $message->addTo(Yii::app()->user->name);
             $message->from = $customerModel->customer_email;
             Yii::app()->mail->send($message);
             $this->redirect(array('view', 'id' => $model->order_id));
         } else {
             echo "booking failed";
         }
     }
 }
Example #3
0
 public function beforeSave()
 {
     if (Product::model()->exists('id = :product_id', [":product_id" => $this->product_id])) {
         $this->variant_ids = array_filter($this->variant_ids);
         // удаляем варианты, которые не были выбраны, старые не трогаем, чтобы оставить данные, на случай, если вариант был удален из системы
         foreach ($this->oldVariants as $key => $var) {
             if (!in_array($var['id'], $this->variant_ids)) {
                 unset($this->oldVariants[$key]);
             }
         }
         $oldVariantIds = array_map(function ($x) {
             return $x['id'];
         }, $this->oldVariants);
         $newVariants = [];
         foreach ($this->variant_ids as $varId) {
             if (!in_array($varId, $oldVariantIds)) {
                 /* @var $variant ProductVariant */
                 $variant = ProductVariant::model()->findByPk($varId);
                 if ($variant) {
                     // сохраняем информацию на случай удаления варианта из системы
                     $newVariants[] = array_merge($variant->attributes, ['attribute_name' => $variant->attribute->name, 'attribute_title' => $variant->attribute->title, 'optionValue' => $variant->getOptionValue()]);
                 }
             }
         }
         $combinedVariants = array_merge($this->oldVariants, $newVariants);
         $this->variants = serialize($combinedVariants);
     }
     return parent::beforeSave();
 }
Example #4
0
 /**
  * get the total number according the search criteria
  *
  * @author                                              youzhao.zxw<*****@*****.**>
  * @param   string         $infoType                    bug,case or result
  * @param   int            $productId                   product id
  * @param   string         $whereStr                    search condition string
  * @param   boolean        $isAllBasicField             is the search condition only in basic info table
  * @return  int                                         total number
  *
  */
 public static function getTotalFoundNum($infoType, $productId, $whereStr, $isAllBasicField = false)
 {
     $basicTableName = $infoType . 'view';
     if (empty($productId)) {
         $accessIdArr = Yii::app()->user->getState('visit_product_id');
         $productFilter = 'product_id in (' . join(',', $accessIdArr) . ')';
     } else {
         $productFilter = 'product_id=' . $productId;
     }
     $searchSql = $productFilter;
     if ('' != $whereStr) {
         $searchSql .= ' and ' . $whereStr;
     }
     if ('1 = 1' == trim($whereStr)) {
         $rawData = Yii::app()->db->createCommand()->select('count(*) as totalNum')->from('{{' . $infoType . '_info}}')->where($searchSql)->queryRow();
     } else {
         if (empty($productId)) {
             $rawData = Yii::app()->db->createCommand()->select('count({{' . $basicTableName . '}}.id) as totalNum')->from('{{' . $basicTableName . '}}')->where($searchSql)->queryRow();
         } else {
             $productInfo = Product::model()->findByPk($productId);
             if (!empty($productInfo) && "(({{bugview}}.module_name LIKE '" . $productInfo['name'] . "/%' or {{bugview}}.module_name = '" . $productInfo['name'] . "'))" == $whereStr) {
                 $rawData = Yii::app()->db->createCommand()->select('count(*) as totalNum')->from('{{' . $infoType . '_info}}')->where($productFilter)->queryRow();
             } else {
                 if ($isAllBasicField) {
                     $rawData = Yii::app()->db->createCommand()->select('count({{' . $basicTableName . '}}.id) as totalNum')->from('{{' . $basicTableName . '}}')->where($searchSql)->queryRow();
                 } else {
                     $addOnTableName = 'etton' . $infoType . '_' . $productId;
                     $rawData = Yii::app()->db->createCommand()->select('count({{' . $basicTableName . '}}.id) as totalNum')->from('{{' . $basicTableName . '}}')->join('{{' . $addOnTableName . '}}', '{{' . $basicTableName . '}}' . '.id=' . '{{' . $addOnTableName . '}}' . '.' . $infoType . '_id and ' . $productFilter)->where($searchSql)->queryRow();
                 }
             }
         }
     }
     return $rawData['totalNum'];
 }
 /**
  * View a particular product, with localizations and images associated.
  */
 public function actionIndex()
 {
     if (Yii::app()->user->isGuest) {
         $cache_id = Yii::app()->request->hostInfo . " Api/LayoutController:[indexForLanguageGuest] " . Yii::app()->language;
         $cache_duration = 600;
         //10800;
     } else {
         $cache_id = Yii::app()->request->hostInfo . " Api/LayoutController:[indexForLanguageUser] " . Yii::app()->language . " - " . Yii::app()->user->user->id;
         $cache_duration = 1600;
     }
     $layout_array = Yii::app()->cache->get($cache_id);
     if (!$layout_array) {
         $layout_parameters = array('storeid' => Yii::app()->params['outbound_api_user'], 'storekey' => Yii::app()->params['outbound_api_secret'], 'locale' => Yii::app()->language . "_CA", 'layout_type' => Yii::app()->params['mainPageLayout']);
         if (!Yii::app()->user->isGuest) {
             $layout_parameters["email"] = Yii::app()->user->user->email;
         }
         $output = Yii::app()->curl->get("https://kle-en-main.com/CloudServices/index.php/Layout/boukem/mobileIndex", $layout_parameters);
         $base_dict = json_decode($output);
         $layout_array = array();
         foreach ($base_dict->promoted as $promoted_id) {
             $product = Product::model()->findByPk($promoted_id);
             if ($product && $product->visible == 1 && $product->productLocalization) {
                 $layout_array[] = $product->getStructuredProductArray();
             }
         }
         Yii::app()->cache->set($cache_id, $layout_array, $cache_duration);
     }
     $this->renderJSON($layout_array);
 }
 public function process()
 {
     $model = \Product::model();
     foreach ($this->products as $product) {
         $model->saveItem($product, $this->popularProductIds);
     }
 }
 public function safeUp()
 {
     $this->createTable('{{store_product_attribute_value}}', ['id' => 'pk', 'product_id' => 'INTEGER NOT NULL', 'attribute_id' => 'INTEGER NOT NULL', 'number_value' => 'REAL', 'string_value' => 'VARCHAR(250)', 'text_value' => 'TEXT', 'option_value' => 'INTEGER', 'create_time' => 'DATETIME'], $this->getOptions());
     //fk
     $this->addForeignKey('{{fk_product_attribute_product}}', '{{store_product_attribute_value}}', 'product_id', '{{store_product}}', 'id', 'CASCADE');
     $this->addForeignKey('{{fk_product_attribute_attribute}}', '{{store_product_attribute_value}}', 'attribute_id', '{{store_attribute}}', 'id', 'CASCADE');
     $this->addForeignKey('{{fk_product_attribute_option}}', '{{store_product_attribute_value}}', 'option_value', '{{store_attribute_option}}', 'id', 'CASCADE');
     //ix
     $this->createIndex('{{ix_product_attribute_number_value}}', '{{store_product_attribute_value}}', 'number_value');
     $this->createIndex('{{ix_product_attribute_string_value}}', '{{store_product_attribute_value}}', 'string_value');
     //перенести аттрибуты
     $attributes = Yii::app()->getDb()->createCommand('SELECT * FROM {{store_product_attribute_eav}}')->queryAll();
     $modelsAttr = [];
     foreach ($attributes as $attribute) {
         $product = Product::model()->findByPk($attribute['product_id']);
         if (null === $product) {
             continue;
         }
         if (!isset($modelsAttr[$attribute['attribute']])) {
             $model = Attribute::model()->find('name = :name', [':name' => $attribute['attribute']]);
             if (null === $model) {
                 continue;
             }
             $modelsAttr[$attribute['attribute']] = $model;
         }
         $value = new AttributeValue();
         $value->store($modelsAttr[$attribute['attribute']]->id, $attribute['value'], $product);
     }
     $this->dropTable('{{store_product_attribute_eav}}');
 }
Example #8
0
 /**
  * 获取订单的商品列表.
  * @param $orderId
  */
 public function getOrderProductByOrderId($orderId)
 {
     if (empty($orderId)) {
         return '';
     }
     $list = OrderProduct::model()->findAllByAttributes(array('order_id' => $orderId));
     if (empty($list)) {
         return '';
     }
     // todo 图片待处理
     $newList = array();
     foreach ($list as $row) {
         $temp = $row->getAttributes();
         if ($row->type == 1) {
             $temp['images']['cover'] = '/images/public/tab.png';
         } elseif ($row->type == 2) {
             $zineInfo = Zine::model()->findByPk($row['product_id']);
             if ($zineInfo) {
                 $temp['images']['cover'] = '/images/zine/' . $zineInfo['mcover'];
             } else {
                 $temp['images']['cover'] = '';
             }
         } else {
             $temp['images'] = Product::model()->getProductFaceImageByProductId($row->product_id);
         }
         $temp['total_price'] = $temp['sell_price'] * $temp['quantity'];
         $newList[$row->id] = $temp;
     }
     return $newList;
 }
 public function actionUpdate()
 {
     $pictures = array();
     $lid = Yii::app()->request->getParam('lid');
     Until::isUpdateValid(array($lid), $this->companyId, $this);
     //0,表示企业任何时候都在云端更新。
     $criteria = new CDbCriteria();
     $criteria->with = 'productImg';
     $criteria->addCondition('t.lid=:lid and t.dpid=:dpid and t.delete_flag=0 ');
     $criteria->order = ' t.lid desc ';
     $criteria->params[':lid'] = $lid;
     $criteria->params[':dpid'] = $this->companyId;
     $model = Product::model()->find($criteria);
     if (Yii::app()->request->isPostRequest) {
         $postData = Yii::app()->request->getPost('productImg');
         if (ProductPicture::saveImg($this->companyId, $lid, $postData)) {
             Yii::app()->user->setFlash('success', yii::t('app', '修改成功'));
             $this->redirect(array('productImg/index', 'companyId' => $this->companyId));
         }
     }
     if (!empty($model->productImg)) {
         foreach ($model->productImg as $pic) {
             array_push($pictures, $pic->pic_path);
         }
     }
     $this->render('updateProductImg', array('model' => $model, 'pictures' => $pictures));
 }
Example #10
0
 public function cacheCreateFilter($models)
 {
     $array = array('stext');
     $r = $this->checkCacheSearchFields($array);
     if ($r === false) {
         false;
     }
     $returnArray = array();
     $prodcatsID = $this->searchFields['prodcat_id'] ? explode(',', $this->searchFields['prodcat_id']) : null;
     $products = Product::model()->cache()->findAllInArray();
     foreach ($models as $k => $model) {
         $bool = true;
         if ($this->searchFields['stext']) {
             $string = $model['product_id'] . $model['product_name'] . $model['product_sku'] . $model['product_shipping_sku'];
             $pos = strpos($string, $this->searchFields['stext']);
             if ($pos === false) {
                 $bool = false;
             }
         }
         if ($prodcatsID) {
             if (!in_array($model['prodcat_id'], $prodcatsID)) {
                 $bool = false;
             }
         }
         if ($bool) {
             $model['product_next_sky'] = isset($products[$model['product_next_id']]['product_sku']) ? $products[$model['product_next_id']]['product_sku'] : '';
             $returnArray[] = $model;
         }
     }
     return $returnArray;
 }
 public function run()
 {
     $model = Product::model()->findAll('image is not null');
     $module = Yii::app()->getModule('exchange1c');
     $basePath = Yii::app()->uploadManager->getBasePath();
     // путь до папки uploads public_html
     $path = Yii::getPathOfAlias('webroot') . '/..' . $module->pathOut;
     // путь до папки out 1c
     $string = "Код товара;Имя файла;Размер в байтах;Время последней модификации\n";
     // Описание информации
     foreach ($model as $key => $value) {
         $file = $basePath . '/' . $value->uploadPath . '/' . $value->image;
         if (file_exists($file)) {
             $info = stat($file);
             $nameImage = $value->image;
             $code = substr($value->image, 0, 11);
             $size = $info['size'];
             $mtime = $info['mtime'];
             $string .= "{$code};{$nameImage};{$size};{$mtime}\n";
         }
     }
     file_put_contents($path . '/images.csv', $string);
     if ($this->redirect) {
         Yii::app()->getController()->redirect(['/exchange1c/exchangeBackend/images']);
     }
     echo $string;
 }
 public function run()
 {
     if (empty($this->model) || empty($this->attribute) || !$this->model->hasAttribute($this->attribute) || $this->model->{$this->attribute} == '') {
         return;
     }
     $productIds = trim($this->model->{$this->attribute});
     $productIds = trim($productIds, ',');
     $productIds = explode(',', $productIds);
     if (empty($productIds)) {
         return;
     }
     array_walk($productIds, function ($data) {
         return (int) trim($data);
     });
     $criteria = new CDbCriteria();
     $criteria->addInCondition('t.id', $productIds);
     //$criteria->order = 't.category_id ASC, t.sort ASC';
     $criteria->order = 'FIELD(t.id, ' . implode(',', $productIds) . ')';
     if ($this->limit > 0) {
         $criteria->limit = (int) $this->limit;
     }
     $models = Product::model()->published()->findAll($criteria);
     //Yii::app()->user->setState('activeProductsList', CJSON::encode(Product::model()->getProductsTotalList(true, $criteria)));
     $this->render($this->view, array('models' => $models, 'model' => $this->model, 'title' => $this->title));
 }
 /**
  * @param Event $event
  */
 public static function onGenerate(Event $event)
 {
     $generator = $event->getGenerator();
     $provider = new CActiveDataProvider(Product::model()->published());
     foreach (new CDataProviderIterator($provider) as $item) {
         $generator->addItem(ProductHelper::getUrl($item, true), strtotime($item->update_time), SitemapHelper::FREQUENCY_DAILY, 0.5);
     }
 }
Example #14
0
 /**
  * This function generates the products grid
  * based on the criteria. It also generates the
  * pagination object need for the users to navigate
  * through products.
  *
  * @return void
  */
 public function generateProductGrid()
 {
     $this->_numberOfRecords = Product::model()->count($this->_productGridCriteria);
     $this->_pages = new CPagination($this->_numberOfRecords);
     $this->_pages->setPageSize(CPropertyValue::ensureInteger(Yii::app()->params['PRODUCTS_PER_PAGE']));
     $this->_pages->applyLimit($this->_productGridCriteria);
     $this->_productsGrid = self::createBookends(Product::model()->findAll($this->_productGridCriteria));
 }
Example #15
0
 public function run()
 {
     $criteria = new CDbCriteria();
     $criteria->order = "id DESC";
     $criteria->limit = 5;
     //        $criteria->addCondition("is_deleted = 0");
     $this->render('lastProduct', array('product' => Product::model()->findAll($criteria)));
 }
Example #16
0
 /**
  * Set the product for this order-row
  * @param string $sku
  * @return \Afosto\ActiveAnts\OrderItem
  */
 public function setSku($sku, $validate = true)
 {
     if ($validate && Product::model()->isNewRecord(array('sku' => $sku))) {
         throw new ApiException('Product not available at ActiveAnts');
     }
     $this->sku = $sku;
     return $this;
 }
 /**
  * @param Event $event
  */
 public static function onGenerate(Event $event)
 {
     $generator = $event->getGenerator();
     $provider = new CActiveDataProvider(Product::model()->published());
     foreach (new CDataProviderIterator($provider) as $item) {
         $generator->addItem(Yii::app()->createAbsoluteUrl('/store/catalog/show', ['name' => $item->slug]), strtotime($item->update_time), SitemapHelper::FREQUENCY_DAILY, 0.5);
     }
 }
 /**
  * Returns the data model based on the primary key given in the POST payload.
  * If the data model is not found, an HTTP exception will be raised.
  * @param array $payload the entire request payload
  * @return Product the loaded model
  * @throws CHttpException
  */
 public function loadModel($id)
 {
     $model = Product::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
 public function processGet()
 {
     $list = Product::model()->findAll();
     $items = array();
     foreach ($list as $p) {
         array_push($items, array("id" => $p->id, "name" => $p->name, "description" => $p->description, "images" => $p->images));
     }
     Response::ok(CJSON::encode(array("version" => "xxxxxxxxxxxxxxxxxxx", "items" => $items)));
 }
 public function actionUpdate($product_id, $quantity)
 {
     $product = Product::model()->findByPk($product_id);
     if (!is_null($product)) {
         $shoppingCart = Yii::app()->customer->getShoppingCart();
         $shoppingCart->add($product->product_id, intval($quantity));
         $this->redirect(array('index'));
     }
 }
 public function actionView()
 {
     if (!empty($_GET['subcategory']) || !empty($_GET['category'])) {
         $product = Product::model()->with('productDescriptions')->find('productDescriptions.link=:link', array(':link' => $_GET['product']));
         $this->render('product', array('product' => $product, 'options' => $this->loadProductOption($product->id)));
     } else {
         throw new CHttpException(400, Yii::t('info', 'Your request is invalid.'));
     }
 }
Example #22
0
 private function getActiveProductId()
 {
     $activeProductArr = Product::model()->findAllByAttributes(array('is_dropped' => '0'));
     $productIdArr = array();
     foreach ($activeProductArr as $product) {
         $productIdArr[] = $product['id'];
     }
     return join(',', $productIdArr);
 }
 protected function tearDown()
 {
     //        /*delete all productOrders*/
     ProductOrders::model()->deleteAll();
     /*delete all products*/
     Product::model()->deleteAll();
     /*delete all orders*/
     Orders::model()->deleteAll();
     parent::tearDown();
 }
Example #24
0
 public function findAllProducts()
 {
     $products = array();
     foreach ($this->_products as $product_id => $quantity) {
         $product = Product::model()->findByPk($product_id);
         if (!is_null($products)) {
             $products[] = $product;
         }
     }
     return $products;
 }
 public function tearDown()
 {
     /*delete all productOrders*/
     ProductOrders::model()->deleteAll();
     /*delete all products*/
     Product::model()->deleteAll();
     /*delete all orders*/
     Orders::model()->deleteAll();
     /*delete all customers*/
     Customer::model()->deleteAll();
 }
Example #26
0
 public function productImageThumb($id)
 {
     $p = Product::model()->findByPk($id);
     if (!empty($p)) {
         $imgs = $p->images;
         if (isset($imgs[0]->source)) {
             return $imgs[0]->source;
         }
     }
     return;
 }
 public function actionRemove($id)
 {
     $id = (int) $_GET['id'];
     $model = Product::model()->findByPk($id);
     if ($model !== null) {
         Yii::app()->favorite->remove($model->getId());
     }
     if (Yii::app()->getRequest()->getIsAjaxRequest()) {
         Yii::app()->ajax->success();
     } else {
         $this->redirect($model->url);
     }
 }
 public function actionList($company_id = 0)
 {
     if ($company_id == 0) {
         $company_id = Yii::app()->getUser()->getProfile()->company_id;
     }
     $this->module->setImport(['application.modules.store.models.*']);
     $criteria = new CDbCriteria();
     $criteria->with = ['user' => ['joinType' => 'INNER JOIN', 'condition' => 'user.company_id = :company_id']];
     $criteria->params = [':company_id' => $company_id];
     $criteria->order = 't.id DESC';
     $Product = Product::model()->findAll($criteria);
     $this->render('list', ['Product' => $Product]);
 }
Example #29
0
 public function actionDeactivate()
 {
     Yii::app()->setImport(['application.modules.cargo.models.*']);
     $condition = new CDbCriteria();
     $condition->addCondition('TO_DAYS(NOW()) - TO_DAYS(`deleted_status_date`) > 15');
     Product::model()->updateAll(['deleted_status' => Product::DEL_SATUS_ARCHIVE], $condition);
     Cargo::model()->updateAll(['deleted_status' => Cargo::DEL_SATUS_ARCHIVE], $condition);
     Reis::model()->updateAll(['deleted_status' => Reis::DEL_SATUS_ARCHIVE], $condition);
     Sklad::model()->updateAll(['deleted_status' => Sklad::DEL_SATUS_ARCHIVE], $condition);
     Custom::model()->updateAll(['deleted_status' => Custom::DEL_SATUS_ARCHIVE], $condition);
     Insurance::model()->updateAll(['deleted_status' => Insurance::DEL_SATUS_ARCHIVE], $condition);
     SpecialTechnique::model()->updateAll(['deleted_status' => SpecialTechnique::DEL_SATUS_ARCHIVE], $condition);
 }
 protected function beforeAction($action)
 {
     $actions = array('index', 'create');
     if (in_array($action->id, $actions)) {
         $this->item_id = (int) Yii::app()->getRequest()->getParam('item_id');
         if (!$this->item_id) {
             throw new CHttpException(400, 'Не установлен ID товара');
         }
         if (($this->item = Product::model()->findByPk($this->item_id)) === null) {
             throw new CHttpException(404, 'Товар не найден');
         }
     }
     return parent::beforeAction($action);
 }