C
C
cat_crash2017-02-13 06:52:09
Yii
cat_crash, 2017-02-13 06:52:09

How to make Yii2 model attributes dynamic?

Dear universal mind, help me solve the problem:
I have Yii2 and a fastened data model through mongodb \ ActiveRecord
I want to give people freedom of action so that through a simple web interface they can add records with their key-> value pairs
Restrictions:
- Store in Mongo exactly attributes { $key}->{$value}, i.e. pushing $attributes into a variable predefined in the model is not a solution to the problem
- There is no way to list all possible $key values ​​in the model sources, because there is no limit to human creativity
Intuitively I suppose that it is necessary to play with __get, __set but so far it has not brought any result. Or swears that the property is not defined, or returns empty values ​​for all properties (overriding them in __set)
Ps There is a similar topic tostackoverflow.com/questions/38356701/yii2-adding-a... (1st case) - but in my case it didn't work out for some reason.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Skripchenko, 2017-02-16
@cat_crash

CREATE TABLE `storage` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `key` varchar(255) DEFAULT NULL,
  `value` text,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`,`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

public function __get($name)
    {
        try{
            return parent::__get($name); 
        }
        catch(Exception $e){
            $sql = 'SELECT `s`.`value` FROM `storage` AS `s` WHERE `s`.`user_id` = :uid AND `key` = :key ';
            return Yii::$app->db->createCommand($sql)->bindValues([
                ':uid' => $userId, 
                ':key' => $name
            ])->queryScalar();
        }
    }

public function __set($name, $value)
    {
        try{
            parent::__set($name, $value); 
        }
        catch(Exception $e){
            if($this->$name){
                $sql = 'UPDATE `storage` AS `s` SET `s`.`value` = :value WHERE `s`.`key` = :key AND `s`.`user_id` = :uid ';
            }
            else{
                $sql = 'INSERT INTO `storage` (`user_id`,`key`,`value`) VALUES (:uid,:key,:value)';
            }
            Yii::$app->db->createCommand($sql)->bindValues([
                ':value' => $value,
                ':key' => $name,
                ':uid' => $userId 
            ])->execute();
        }
    }

$userId ID of the desired user

M
Maxim Timofeev, 2017-02-13
@webinar

https://github.com/phemellc/yii2-settings

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question