Ответы пользователя по тегу Yii
  • Как изменить массив $config?

    @dimabdc
    Если Вам нужен доступ к нескольким базам, то создай 2 конфига подключения:
    db.php
    <?php
    return [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db',
        'username' => 'root',
        'password' => '12345',
    ];

    db2.php
    <?php
    return [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=serser;dbname=db',
        'username' => 'root',
        'password' => '54321',
    ];

    и подключите их в web.php
    'db' => require(__DIR__ . '/db.php'),
    'db2' => require(__DIR__ . '/db2.php'),

    Соответственно для выборки из первой базы будет
    $posts = Yii::$app->db->createCommand('SELECT * FROM post')->queryAll();
    , из второй
    $posts = Yii::$app->db2->createCommand('SELECT * FROM post')->queryAll();


    А если Вам вообще нужны будут разные конфигурации, то создайте 2 конфига web.php и web2.php и меняйте их в web/index.php, например по условию GET параметра
    Ответ написан
  • Почему не работает валидация правил с match в Yii2?

    @dimabdc
    уберите из [] знак ^
    Matches any character except for an a, b or c
    /[^abc]+/
    Ответ написан
  • Как упростить функции контроллера?

    @dimabdc
    Можно (и нужно) выделять одинаковые куски кода в отдельные функции:
    /**
         * view Month
         */
        public function actionMonth()
        {
            $rangeData = $this->_getDateRange();
    
            return $this->render('month', [
                'result' => $this->_getSheel(),
                'firstDay' => $rangeData['firstDay'],
            ]);
    
        }
    
        /**
         * view Company
         */
        public function actionCompany()
        {
            $company =$_GET['company']; // с 1 месяца по 12
            $rangeData = $this->_getDateRange();
    
            //  VarDumper::dump($res);
            return $this->render('company', [
                // 'materials' => $materials,
                'company' => $company,
                'result' => $this->_getSheel('parent_company', $company),
                'firstDay' => $rangeData['firstDay'],
            ]);
    
        }
        
        /**
         *
         * view Address
         */
        public function actionAddress()
        {
            $company =$_GET['id'];
            $addreses =  Sheel::findAll(['id_sheel' => $company]);
            foreach ($addreses as $key=>$one){
                $addres = $one->address;
            };
            $rangeData = $this->_getDateRange();
    
            return $this->render('address', [
                'result' => $result,
                'firstDay' => $rangeData['firstDay'],
            ]);
    
        }
    
        /**
         * Get date range
         * 
         * @return array
         */
        protected function _getDateRange()
        {
            $month = date('n', $_GET['time']); // с 1 месяца по 12
            $year = date('Y', $_GET['time']); // 2011
    
            return [
                'firstDay' => date("Y-m-d", mktime(0, 0, 0, $month, 1, $year)),
                'lastDay' => date("Y-m-d", mktime(0, 0, 0, $month + 1, 1, $year))
            ];
        }
    
        /**
         * Get sheel
         * 
         * @param mixed $name
         * @param mixed $value
         * @return ArrayDataProvider
         */
        protected function _getSheel($name = null, $value = null)
        {
            $rangeData = $this->_getDateRange();
    
            $params = [
                ':time1' => $rangeData['firstDay'],
                ':time2' => $rangeData['lastDay'],
            ];
            $where = 'date_execution >= :time1 AND date_execution < :time2';
    
            if ($name) {
                $where .= " AND :$name = :name";
                $params[":$name"] = $value;
            }
    
            $customers = Sheel::find()
                ->andWhere($where, $params)
                ->orderBy('date_execution DESC')
                ->joinWith('recipies')
                ->with('company')
                ->all();
            $res = [];
            foreach ($customers as &$item) {
                $res[] = [
                    'id_sheel'=>$item->id_sheel,
                    'parent_recipies'=>$item->parent_recipies,
                    'id_company'=>$item->company->id_company,
                    'name_company' => $item->company->name_company,
                    'address' => $item->address,
                    'recipies' =>
                        $item->recipies->porous_recipies . " " .
                        $item->recipies->size_min . " " .
                        $item->recipies->type_recipies . " " .
                        $item->recipies->brand_recipies . " " .
                        "№ " . $item->recipies->number_recipies,
                    'amount_sheel' => $item->amount_sheel,
                    'date_execution' => $item->date_execution,
                ];
            }
            return new ArrayDataProvider(['allModels' => $res]);
        }
    Ответ написан
    Комментировать
  • Yii2 RBAC как исключить некоторые права дочерней роли?

    @dimabdc
    Можно только через костыль.
    У Вас ошибка в наследовании прав, наследование должно быть в порядке возрастания базовых полномочий, т.е. guest->user->moderator->admin.
    Ответ написан