0
votes

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

2
you are using same $userid for update record , so basically you are updating same record again and again. - Insane Skull
Yes, but I want that. The foreach will be give diferent value. I simplified the update because doesn't work. If work once I will be happy. But update no touch the record. Stay "null", stay 1. - Cipo
also you don't have any required field. - Insane Skull

2 Answers

3
votes

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.

0
votes

Queue your search for the record and set the new value:

$userId = 1;
$user = Users::findOne($userId);
$user->ramount = 22;

Try using the save() method:

if ($user->save()) {
  echo "update successful";
} else {
  echo "update failed";
}

PD: The return value of save method is boolean(true or false).