简体   繁体   中英

Can not update php activerecord: model is read-only

I'm trying to update the user details table using php activerecord but everytime I get this error

::save() cannot be invoked because this model is set to read only

I can insert to the same table but I can't update

Details.php

<?php
class Details extends ActiveRecord\Model
{
public static $table_name='details';
public static $primary_key='id_user_detail';

public function before_create()
{
   $this->date_created      = date("Y-m-d H:i:s");
   $this->date_modified     = date("Y-m-d H:i:s");
}

public function before_update()
{
   $this->date_modified    = date("Y-m-d H:i:s");
}

}?>

profile-edit.php

 $sql   = " select * from details where id_user_detail=1";
 $user  = Details::find_by_sql($sql);
 $user->user_fname="test";
 $user->save();

How can I do an update?

The fact that it is read-only is expected. see the manual for custom-sql finders

This will render your model as readonly so that you cannot use any write methods on your returned model(s).

There's no need to use this complicated finder, just use the AR model:

 $user  = Details::find(1);
 $user->user_fname="test";
 $user->save();

This works because id_user_detail is your primary key. If you want to find on another field, lets say user_fname , do this:

 $user  = Details::find_by_user_fname('test');
 $user->user_fname="test2";
 $user->save();

Read up on those finders and on how to use them, as you should avoid the sql-finder.

This happened because $user contains an array, the save() method is used for object only. You can use other finders, but when it's a complex query, you can use a foreach and then use a finder by default.

You probably trying to change class attributes before you have instantiate the class.

Details::find_by_sql() should return a new Details instance. For Example :

public function find_by_sql($sql) {
   //execute sql
   if( some thing is returned ) {
      $details = new Details();
      $details->setByResult($sql_result)

      return $details;
   }

   return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM