Search code examples
activerecordyii2updatemodel

yii 2.0 ActiveRecord update doesn't work


I'm a begginer in Yii 2. I'm trying a simple user update, with activerecord, but the update() method doesn't do anything. The update() return back with "true", always "success", but the DB record didn't change.

Controller:

use app\models\Users;

.....

$userId = 1;
foreach ($array as $value) {
   $user = Users::findOne($userId);
   //$user->ramount = ($user->ramount + $value->ramunt);
   $user->ramount = 22;
   if ($user->update() !== false) {
     echo "update successful";
   } else {
     echo "update failed";
   }

   //$user = Users::findOne($userId);
   //$user->updateCounters(['ramount' => 22]);
 }

I simplified the update because didn't work. The updateCounters() method works perfectly, but I don't want to use that.

Model

namespace app\models;

use yii\base\Model;

class Users extends \yii\db\ActiveRecord
{
    public $id;
    public $email;
    public $username;
    public $ramount;

    public function attributeLabels() {
        return [
            'id' => 'User ID',
            'username' => 'Your name',
            'email' => 'Your email address',
            'ramount' => 'Resources',
        ];
    }

    public static function tableName() {
        return 'users';
    }

    public function rules() {
        return [
            [['username'], 'string', 'max'=>60],
            [['email'], 'string', 'max'=>120],
            [['ramount'],'number','max'=>999999],
        ];
    }
}

No error in apache log, no error in yii runtime log. Thx all tips


Solution

  • You have defined in your model class

    class Users extends \yii\db\ActiveRecord
    {
        public $id;
        public $email;
        public $username;
        public $ramount;
        ....
    }
    

    Remove those variables since they override the attributes that ActiveRecord works on.

    Yii Guide says:

    Note: The Active Record attributes are named after the associated table columns in a case-sensitive manner. Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.