ProductMongodb.php 24.3 KB
Newer Older
_
__FresHmaN 已提交
1 2 3 4 5 6 7 8 9 10 11 12
<?php
/**
 * FecShop file.
 *
 * @link http://www.fecshop.com/
 * @copyright Copyright (c) 2016 FecShop Software LLC
 * @license http://www.fecshop.com/license/
 */

namespace fecshop\services\product;

use fecshop\models\mongodb\Product;
T
Terry 已提交
13
use fecshop\services\Service;
_
__FresHmaN 已提交
14 15 16
use Yii;

/**
17
 * Product ProductMysqldb Service
_
__FresHmaN 已提交
18 19 20
 * @author Terry Zhao <2358269014@qq.com>
 * @since 1.0
 */
T
Terry 已提交
21
class ProductMongodb extends Service implements ProductInterface
_
__FresHmaN 已提交
22 23
{
    public $numPerPage = 20;
T
Terry 已提交
24
    
25 26 27 28
    
    protected $_productModelName = '\fecshop\models\mongodb\Product';
    protected $_productModel;
    
T
Terry 已提交
29 30
    public function init(){
        parent::init();
31 32 33
        list($this->_productModelName,$this->_productModel) = \Yii::mapGet($this->_productModelName);  
    }
    
_
__FresHmaN 已提交
34 35 36 37
    public function getPrimaryKey()
    {
        return '_id';
    }
38 39 40 41
    /**
     * 得到分类激活状态的值
     */
    public function getEnableStatus(){
T
Terry 已提交
42 43
        $model = $this->_productModel;
        return $model::STATUS_ENABLE;
44 45
    }
    
T
Terry 已提交
46 47
    
    
_
__FresHmaN 已提交
48 49 50
    public function getByPrimaryKey($primaryKey)
    {
        if ($primaryKey) {
T
Terry 已提交
51
            return $this->_productModel->findOne($primaryKey);
_
__FresHmaN 已提交
52
        } else {
53
            return new $this->_productModelName();
_
__FresHmaN 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67
        }
    }

    /**
     * @property $sku|array
     * @property $returnArr|bool 返回的数据是否是数组格式,如果设置为
     *		false,则返回的是对象数据
     * @return array or Object
     *               通过sku 获取产品,一个产品
     */
    public function getBySku($sku, $returnArr = true)
    {
        if ($sku) {
            if ($returnArr) {
T
Terry 已提交
68
                $product = $this->_productModel->find()->asArray()
_
__FresHmaN 已提交
69 70 71
                    ->where(['sku' => $sku])
                    ->one();
            } else {
T
Terry 已提交
72
                $product = $this->_productModel->findOne(['sku' => $sku]);
_
__FresHmaN 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            }
            $primaryKey = $this->getPrimaryKey();
            if (isset($product[$primaryKey]) && !empty($product[$primaryKey])) {
                return $product;
            }
        }
    }

    /**
     * @property $spu|array
     * @property $returnArr|bool 返回的数据是否是数组格式,如果设置为
     *		false,则返回的是对象数据
     * @return array or Object
     *               通过spu 获取产品数组
     */
    public function getBySpu($spu, $returnArr = true)
    {
        if ($spu) {
            if ($returnArr) {
T
Terry 已提交
92
                return $this->_productModel->find()->asArray()
_
__FresHmaN 已提交
93 94 95
                    ->where(['spu' => $spu])
                    ->all();
            } else {
T
Terry 已提交
96
                return $this->_productModel->find()
_
__FresHmaN 已提交
97 98 99 100 101
                    ->where(['spu' => $spu])
                    ->all();
            }
        }
    }
102 103
    
    
_
__FresHmaN 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

    /*
     * example filter:
     * [
     * 		'numPerPage' 	=> 20,
     * 		'pageNum'		=> 1,
     * 		'orderBy'	=> ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
     * 		'where'			=> [
                ['>','price',1],
                ['<=','price',10]
     * 			['sku' => 'uk10001'],
     * 		],
     * 	'asArray' => true,
     * ]
     */
    public function coll($filter = '')
    {
T
Terry 已提交
121
        $query = $this->_productModel->find();
_
__FresHmaN 已提交
122 123 124 125
        $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);

        return [
            'coll' => $query->all(),
T
Terry 已提交
126
            'count'=> $query->limit(null)->offset(null)->count(),
_
__FresHmaN 已提交
127 128 129 130 131 132 133 134 135 136
        ];
    }

    /**
     * 和coll()的不同在于,该方式不走active record,因此可以获取产品的所有数据的。
     * 走这种方式,可以绕过产品属性组,因为产品属性组需要根据不同的
     * 属性组,在active record 上面附加相应的属性,对api这种不适合。
     */
    public function apicoll()
    {
T
Terry 已提交
137
        $collection = $this->_productModel->find()->getCollection();
_
__FresHmaN 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        $cursor = $collection->find();
        $count = $collection->count();
        $arr = [];
        foreach ($cursor as $k =>$v) {
            $v['_id'] = (string) $v['_id'];
            $arr[$k] = $v;
        }

        return [
            'coll' => $arr,
            'count'=> $count,
        ];
    }

    /**
153 154
     * @property $primaryKey | String 主键
     * @return  array ,和getByPrimaryKey()的不同在于,该方式不走active record,因此可以获取产品的所有数据的。
_
__FresHmaN 已提交
155 156 157
     */
    public function apiGetByPrimaryKey($primaryKey)
    {
T
Terry 已提交
158
        $collection = $this->_productModel->find()->getCollection();
_
__FresHmaN 已提交
159 160 161 162 163 164 165 166 167 168
        $cursor = $collection->findOne(['_id' => $primaryKey]);
        $arr = [];
        foreach ($cursor as $k => $v) {
            $arr[$k] = $v;
        }

        return $arr;
    }

    /**
169
     * @property $product_one | String 产品数据数组。这个要和mongodb里面保存的产品数据格式一致。
_
__FresHmaN 已提交
170 171 172 173
     * 通过api保存产品
     */
    public function apiSave($product_one)
    {
T
Terry 已提交
174
        $collection = $this->_productModel->find()->getCollection();
_
__FresHmaN 已提交
175 176 177 178 179 180
        $collection->save($product_one);

        return true;
    }

    /**
181 182
     * @property $primaryKey | String
     * 通过api删除产品
_
__FresHmaN 已提交
183 184 185
     */
    public function apiDelete($primaryKey)
    {
T
Terry 已提交
186
        $collection = $this->_productModel->find()->getCollection();
_
__FresHmaN 已提交
187 188 189 190 191
        $collection->remove(['_id' => $primaryKey]);

        return true;
    }

192 193 194 195 196 197 198
    /*
     * @property $filter | Array , example filter:
     * [
     * 		'numPerPage' 	=> 20,
     * 		'pageNum'		=> 1,
     * 		'orderBy'	=> ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
     * 		'where'			=> [
T
Terry 已提交
199 200
     *          ['>','price',1],
     *          ['<=','price',10]
201 202
     * 			['sku' => 'uk10001'],
     * 		],
T
Terry 已提交
203
     * 	    'asArray' => true,
204 205
     * ]
     * 得到总数。
_
__FresHmaN 已提交
206 207 208
     */
    public function collCount($filter = '')
    {
T
Terry 已提交
209
        $query = $this->_productModel->find();
_
__FresHmaN 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);

        return $query->count();
    }

    /**
     * @property  $product_id_arr | Array
     * @property  $category_id | String
     * 在给予的产品id数组$product_id_arr中,找出来那些产品属于分类 $category_id
     * 该功能是后台分类编辑中,对应的分类产品列表功能
     * 也就是在当前的分类下,查看所有的产品,属于当前分类的产品,默认被勾选。
     */
    public function getCategoryProductIds($product_id_arr, $category_id)
    {
        $id_arr = [];
        if (is_array($product_id_arr) && !empty($product_id_arr)) {
T
Terry 已提交
226
            $query = $this->_productModel->find()->asArray();
_
__FresHmaN 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240
            $mongoIds = [];
            foreach ($product_id_arr as $id) {
                $mongoIds[] = new \MongoDB\BSON\ObjectId($id);
            }
            //var_dump($mongoIds);
            $query->where(['in', $this->getPrimaryKey(), $mongoIds]);
            $query->andWhere(['category'=>$category_id]);
            $data = $query->all();
            if (is_array($data) && !empty($data)) {
                foreach ($data as $one) {
                    $id_arr[] = $one[$this->getPrimaryKey()];
                }
            }
        }
241
        
_
__FresHmaN 已提交
242 243 244 245 246 247 248 249 250 251 252 253
        return $id_arr;
    }

    /**
     * @property $attr_group | String
     * 根据产品的属性组名,得到属性数组,然后将属性数组附加到Product(model)的属性中。
     */
    public function addGroupAttrs($attr_group)
    {
        $attrInfo = Yii::$service->product->getGroupAttrInfo($attr_group);
        if (is_array($attrInfo) && !empty($attrInfo)) {
            $attrs = array_keys($attrInfo);
T
Terry 已提交
254
            $this->_productModel->addCustomProductAttrs($attrs);
_
__FresHmaN 已提交
255 256 257 258 259 260 261 262 263 264 265 266
        }
    }

    /**
     * @property $one|array , 产品数据数组
     * @property $originUrlKey|string , 产品的原来的url key ,也就是在前端,分类的自定义url。
     * 保存产品(插入和更新),以及保存产品的自定义url
     * 如果提交的数据中定义了自定义url,则按照自定义url保存到urlkey中,如果没有自定义urlkey,则会使用name进行生成。
     */
    public function save($one, $originUrlKey = 'catalog/product/index')
    {
        if (!$this->initSave($one)) {
T
Terry 已提交
267
            return false;
_
__FresHmaN 已提交
268
        }
269
        $one['min_sales_qty'] = (int)$one['min_sales_qty'];
_
__FresHmaN 已提交
270 271 272
        $currentDateTime = \fec\helpers\CDate::getCurrentDateTime();
        $primaryVal = isset($one[$this->getPrimaryKey()]) ? $one[$this->getPrimaryKey()] : '';
        if ($primaryVal) {
T
Terry 已提交
273
            $model = $this->_productModel->findOne($primaryVal);
_
__FresHmaN 已提交
274 275 276
            if (!$model) {
                Yii::$service->helper->errors->add('Product '.$this->getPrimaryKey().' is not exist');

T
Terry 已提交
277
                return false;
_
__FresHmaN 已提交
278 279 280
            }

            //验证sku 是否重复
T
Terry 已提交
281
            $product_one = $this->_productModel->find()->asArray()->where([
_
__FresHmaN 已提交
282 283 284 285 286 287 288
                '<>', $this->getPrimaryKey(), (new \MongoDB\BSON\ObjectId($primaryVal)),
            ])->andWhere([
                'sku' => $one['sku'],
            ])->one();
            if ($product_one['sku']) {
                Yii::$service->helper->errors->add('Product Sku 已经存在,请使用其他的sku');

T
Terry 已提交
289
                return false;
_
__FresHmaN 已提交
290 291
            }
        } else {
292
            $model = new $this->_productModelName();
_
__FresHmaN 已提交
293 294 295 296 297
            $model->created_at = time();
            $model->created_user_id = \fec\helpers\CUser::getCurrentUserId();
            $primaryVal = new \MongoDB\BSON\ObjectId();
            $model->{$this->getPrimaryKey()} = $primaryVal;
            //验证sku 是否重复
T
Terry 已提交
298
            $product_one = $this->_productModel->find()->asArray()->where([
_
__FresHmaN 已提交
299 300 301 302 303
                'sku' => $one['sku'],
            ])->one();
            if ($product_one['sku']) {
                Yii::$service->helper->errors->add('Product Sku 已经存在,请使用其他的sku');

T
Terry 已提交
304
                return false;
_
__FresHmaN 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317
            }
        }
        $model->updated_at = time();
        /*
         * 计算出来产品的最终价格。
         */
        $one['final_price'] = Yii::$service->product->price->getFinalPrice($one['price'], $one['special_price'], $one['special_from'], $one['special_to']);
        $one['score'] = (int) $one['score'];
        unset($one['_id']);
        /**
         * 保存产品
         */
        $saveStatus = Yii::$service->helper->ar->save($model, $one);
318
        
_
__FresHmaN 已提交
319 320 321 322 323 324 325 326 327 328 329
        /*
         * 自定义url部分
         */
        if ($originUrlKey) {
            $originUrl = $originUrlKey.'?'.$this->getPrimaryKey() .'='. $primaryVal;
            $originUrlKey = isset($one['url_key']) ? $one['url_key'] : '';
            $defaultLangTitle = Yii::$service->fecshoplang->getDefaultLangAttrVal($one['name'], 'name');
            $urlKey = Yii::$service->url->saveRewriteUrlKeyByStr($defaultLangTitle, $originUrl, $originUrlKey);
            $model->url_key = $urlKey;
            $model->save();
        }
330 331 332 333 334
        $product_id = $model->{$this->getPrimaryKey()};
        /**
         * 更新产品库存。
         */
        Yii::$service->product->stock->saveProductStock($product_id,$one);
_
__FresHmaN 已提交
335 336 337
        /**
         * 更新产品信息到搜索表。
         */
338
        Yii::$service->search->syncProductInfo([$product_id]);
_
__FresHmaN 已提交
339

T
Terry 已提交
340
        return $model;
_
__FresHmaN 已提交
341 342 343 344 345 346 347
    }

    /**
     * @property $one|array
     * 对保存的数据进行数据验证
     * sku  spu   默认语言name , 默认语言description不能为空。
     */
348
    protected function initSave(&$one)
_
__FresHmaN 已提交
349
    {
T
Terry 已提交
350 351 352 353 354 355
        $primaryKey = $this->getPrimaryKey();
        $PrimaryVal = 1;
        if (!isset($one[$primaryKey]) || !$one[$primaryKey] ) {
            $PrimaryVal = 0;
        }
        if (!$PrimaryVal && (!isset($one['sku']) || empty($one['sku']))) {
_
__FresHmaN 已提交
356 357 358 359
            Yii::$service->helper->errors->add(' sku 必须存在 ');

            return false;
        }
T
Terry 已提交
360
        if (!$PrimaryVal && (!isset($one['spu']) || empty($one['spu']))) {
_
__FresHmaN 已提交
361 362 363 364 365
            Yii::$service->helper->errors->add(' spu 必须存在 ');

            return false;
        }
        $defaultLangName = \Yii::$service->fecshoplang->getDefaultLangAttrName('name');
T
Terry 已提交
366 367 368 369 370
        if($PrimaryVal && $one['name'] && empty($one['name'][$defaultLangName])){
            Yii::$service->helper->errors->add(' name '.$defaultLangName.' 不能为空 ');

            return false;
        }
_
__FresHmaN 已提交
371 372 373 374 375 376
        if (!isset($one['name'][$defaultLangName]) || empty($one['name'][$defaultLangName])) {
            Yii::$service->helper->errors->add(' name '.$defaultLangName.' 不能为空 ');

            return false;
        }
        $defaultLangDes = \Yii::$service->fecshoplang->getDefaultLangAttrName('description');
T
Terry 已提交
377 378 379 380 381
        if($PrimaryVal && $one['description'] && empty($one['description'][$defaultLangDes])){
            Yii::$service->helper->errors->add(' description '.$defaultLangDes.' 不能为空 ');

            return false;
        }
_
__FresHmaN 已提交
382 383 384 385 386
        if (!isset($one['description'][$defaultLangDes]) || empty($one['description'][$defaultLangDes])) {
            Yii::$service->helper->errors->add(' description '.$defaultLangDes.'不能为空 ');

            return false;
        }
387 388 389 390 391 392 393 394
        if (is_array($one['custom_option']) && !empty($one['custom_option'])) {
            $new_custom_option = [];
            foreach ($one['custom_option'] as $k=>$v) {
                $k = preg_replace('/[^A-Za-z0-9\-_]/', '', $k); 
                $new_custom_option[$k] = $v;
            }
            $one['custom_option'] = $new_custom_option;
        }
_
__FresHmaN 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

        return true;
    }

    /**
     * @property $ids | Array or String
     * 删除产品,如果ids是数组,则删除多个产品,如果是字符串,则删除一个产品
     * 在产品产品的同时,会在url rewrite表中删除对应的自定义url数据。
     */
    public function remove($ids)
    {
        if (empty($ids)) {
            Yii::$service->helper->errors->add('remove id is empty');

            return false;
        }
        if (is_array($ids)) {
T
Terry 已提交
412
            $removeAll = 1;
_
__FresHmaN 已提交
413
            foreach ($ids as $id) {
T
Terry 已提交
414
                $model = $this->_productModel->findOne($id);
_
__FresHmaN 已提交
415 416 417 418 419
                if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
                    $url_key = $model['url_key'];
                    // 删除在重写url里面的数据。
                    Yii::$service->url->removeRewriteUrlKey($url_key);
                    // 删除在搜索表(各个语言)里面的数据
420 421
                    Yii::$service->search->removeByProductId($id);
                    Yii::$service->product->stock->removeProductStock($id);
_
__FresHmaN 已提交
422 423 424 425
                    $model->delete();
                    //$this->removeChildCate($id);
                } else {
                    Yii::$service->helper->errors->add("Product Remove Errors:ID:$id is not exist.");
T
Terry 已提交
426
                    $removeAll = 0;
_
__FresHmaN 已提交
427
                }
T
Terry 已提交
428 429 430 431
                
            }
            if (!$removeAll) {
                return false;
_
__FresHmaN 已提交
432 433 434
            }
        } else {
            $id = $ids;
T
Terry 已提交
435
            $model = $this->_productModel->findOne($id);
_
__FresHmaN 已提交
436 437 438 439 440 441
            if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
                $url_key = $model['url_key'];
                // 删除在重写url里面的数据。
                Yii::$service->url->removeRewriteUrlKey($url_key);
                // 删除在搜索里面的数据
                Yii::$service->search->removeByProductId($model[$this->getPrimaryKey()]);
442
                Yii::$service->product->stock->removeProductStock($id);
_
__FresHmaN 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
                $model->delete();
                //$this->removeChildCate($id);
            } else {
                Yii::$service->helper->errors->add("Product Remove Errors:ID:$id is not exist.");

                return false;
            }
        }

        return true;
    }

    /**
     * @property $category_id | String  分类的id的值
     * @property $addCateProductIdArr | Array 分类中需要添加的产品id数组,也就是给这个分类增加这几个产品。
     * @property $deleteCateProductIdArr | Array 分类中需要删除的产品id数组,也就是在这个分类下面去除这几个产品的对应关系。
     * 这个函数是后台分类编辑功能中使用到的函数,在分类中可以一次性添加多个产品,也可以删除多个产品,产品和分类是多对多的关系。
     */
    public function addAndDeleteProductCategory($category_id, $addCateProductIdArr, $deleteCateProductIdArr)
    {
        // 在 addCategoryIdArr 查看哪些产品,分类id在product中已经存在,
        $idKey = $this->getPrimaryKey();
        //var_dump($addCateProductIdArr);
        if (is_array($addCateProductIdArr) && !empty($addCateProductIdArr) && $category_id) {
            $addCateProductIdArr = array_unique($addCateProductIdArr);
            foreach ($addCateProductIdArr as $product_id) {
                if (!$product_id) {
                    continue;
                }
T
Terry 已提交
472
                $product = $this->_productModel->findOne($product_id);
_
__FresHmaN 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
                if (!$product[$idKey]) {
                    continue;
                }
                $category = $product->category;
                $category = ($category && is_array($category)) ? $category : [];
                //echo $category_id;
                if (!in_array($category_id, $category)) {
                    //echo $category_id;
                    $category[] = $category_id;
                    $product->category = $category;
                    $product->save();
                }
            }
        }

        if (is_array($deleteCateProductIdArr) && !empty($deleteCateProductIdArr) && $category_id) {
            $deleteCateProductIdArr = array_unique($deleteCateProductIdArr);
            foreach ($deleteCateProductIdArr as $product_id) {
                if (!$product_id) {
                    continue;
                }
T
Terry 已提交
494
                $product = $this->_productModel->findOne($product_id);
_
__FresHmaN 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
                if (!$product[$idKey]) {
                    continue;
                }
                $category = $product->category;
                if (in_array($category_id, $category)) {
                    $arr = [];
                    foreach ($category as $c) {
                        if ($category_id != $c) {
                            $arr[] = $c;
                        }
                    }
                    $product->category = $arr;
                    $product->save();
                }
            }
        }
    }

    /**
     * 通过where条件 和 查找的select 字段信息,得到产品的列表信息,
     * 这里一般是用于前台的区块性的不分页的产品查找。
     * 结果数据没有进行进一步处理,需要前端获取数据后在处理。
     */
    public function getProducts($filter)
    {
        $where = $filter['where'];
        if (empty($where)) {
            return [];
        }
        $select = $filter['select'];
T
Terry 已提交
525
        $query = $this->_productModel->find()->asArray();
_
__FresHmaN 已提交
526
        $query->where($where);
527
        $query->andWhere(['status' => $this->getEnableStatus()]);
_
__FresHmaN 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        if (is_array($select) && !empty($select)) {
            $query->select($select);
        }

        return $query->all();
    }

    /**
     *[
     *	'category_id' 	=> 1,
     *	'pageNum'		=> 2,
     *	'numPerPage'	=> 50,
     *	'orderBy'		=> 'name',
     *	'where'			=> [
     *		['>','price',11],
     *		['<','price',22],
     *	],
     *	'select'		=> ['xx','yy'],
     *	'group'			=> '$spu',
     * ]
     * 得到分类下的产品,在这里需要注意的是:
     * 1.同一个spu的产品,有很多sku,但是只显示score最高的产品,这个score可以通过脚本取订单的销量(最近一个月,或者
     *   最近三个月等等),或者自定义都可以。
     * 2.结果按照filter里面的orderBy排序
     * 3.由于使用的是mongodb的aggregate(管道)函数,因此,此函数有一定的限制,就是该函数
     *   处理后的结果不能大约32MB,因此,如果一个分类下面的产品几十万的时候可能就会出现问题,
     *   这种情况可以用专业的搜索引擎做聚合工具。
     *   不过,对于一般的用户来说,这个不会成为瓶颈问题,一般一个分类下的产品不会出现几十万的情况。
     * 4.最后就得到spu唯一的产品列表(多个spu相同,sku不同的产品,只要score最高的那个).
     */
    public function getFrontCategoryProducts($filter)
    {
        $where = $filter['where'];
        if (empty($where)) {
            return [];
        }
        $orderBy = $filter['orderBy'];
        $pageNum = $filter['pageNum'];
        $numPerPage = $filter['numPerPage'];
        $select = $filter['select'];
        $group['_id'] = $filter['group'];
        $project = [];
        foreach ($select as $column) {
            $project[$column] = 1;
            $group[$column] = ['$first' => '$'.$column];
573
            
_
__FresHmaN 已提交
574
        }
575
        $group['product_id'] = ['$first' => '$product_id'];
576
        $langCode = Yii::$service->store->currentLangCode;
T
Terry 已提交
577
        
578
        $name_lang  = Yii::$service->fecshoplang->getLangAttrName('name',$langCode);
T
Terry 已提交
579
        $default_name_lang  = Yii::$service->fecshoplang->GetDefaultLangAttrName('name');
580
        $project['name'] = [
T
Terry 已提交
581 582
            $default_name_lang => 1,
            $name_lang => 1,
583
        ];
584
        $project['product_id'] = '$_id';
_
__FresHmaN 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        $pipelines = [
            [
                '$match'    => $where,
            ],
            [
                '$sort' => [
                    'score' => -1,
                ],
            ],
            [
                '$project'    => $project,
            ],
            [
                '$group'    => $group,
            ],
            [
                '$sort'    => $orderBy,
            ],
603
            [
T
Terry 已提交
604
                '$limit'    => Yii::$service->product->categoryAggregateMaxCount,
605
            ],
_
__FresHmaN 已提交
606
        ];
T
Terry 已提交
607
        // ['cursor' => ['batchSize' => 2]]
T
Terry 已提交
608
        $product_data = $this->_productModel->getCollection()->aggregate($pipelines);
_
__FresHmaN 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
        $product_total_count = count($product_data);
        $pageOffset = ($pageNum - 1) * $numPerPage;
        $products = array_slice($product_data, $pageOffset, $numPerPage);

        return [
            'coll' => $products,
            'count' => $product_total_count,
        ];
    }

    /**
     * @property $filter_attr | String 需要进行统计的字段名称
     * @propertuy $where | Array  搜索条件。这个需要些mongodb的搜索条件。
     * 得到的是个属性,以及对应的个数。
     * 这个功能是用于前端分类侧栏进行属性过滤。
     */
    public function getFrontCategoryFilter($filter_attr, $where)
    {
        if (empty($where)) {
            return [];
        }
        $group['_id'] = '$'.$filter_attr;
        $group['count'] = ['$sum'=> 1];
        $project = [$filter_attr => 1];
        $pipelines = [
            [
                '$match'    => $where,
            ],
            [
                '$project'    => $project,
            ],
            [
                '$group'    => $group,
            ],
643
            [
T
Terry 已提交
644
                '$limit'    => Yii::$service->product->categoryAggregateMaxCount,
645
            ], 
_
__FresHmaN 已提交
646
        ];
T
Terry 已提交
647
        $filter_data = $this->_productModel->getCollection()->aggregate($pipelines);
_
__FresHmaN 已提交
648 649 650 651

        return $filter_data;
    }

652 653 654 655 656 657 658 659
    /**
     * @property $spu | String 
     * @property $avag_rate | Int ,平均评星
     * @property $count | Int ,评论次数
     * @property $lang_code | String ,语言简码
     * @property $avag_lang_rate | Int ,语言下平均评星
     * @property $lang_count | Int , 语言下评论次数。
     */
_
__FresHmaN 已提交
660 661
    public function updateProductReviewInfo($spu, $avag_rate, $count, $lang_code, $avag_lang_rate, $lang_count)
    {
T
Terry 已提交
662
        $data = $this->_productModel->find()->where([
_
__FresHmaN 已提交
663 664 665 666 667 668 669 670 671
            'spu' => $spu,
        ])->all();
        if (!empty($data) && is_array($data)) {
            $attrName = 'reviw_rate_star_average_lang';
            $review_star_lang = Yii::$service->fecshoplang->getLangAttrName($attrName, $lang_code);
            $attrName = 'review_count_lang';
            $review_count_lang = Yii::$service->fecshoplang->getLangAttrName($attrName, $lang_code);
            foreach ($data as $one) {
                $one['reviw_rate_star_average'] = $avag_rate;
672 673 674 675 676
                $one['review_count']            = $count;
                $a                              = $one['reviw_rate_star_average_lang'];
                $a[$review_star_lang]           = $avag_lang_rate;
                $b                              = $one['review_count_lang'];
                $b[$review_count_lang]          = $lang_count;
_
__FresHmaN 已提交
677
                $one['reviw_rate_star_average_lang'] = $a;
678
                $one['review_count_lang']       = $b;
_
__FresHmaN 已提交
679 680 681 682 683
                $one->save();
            }
        }
    }
}