Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update only specific fields of an active record in Yii?

I have a model (ActiveRecord) that has 5 properties (DB columns).
I fetch a specific record and populate a form that has 3 fields (two other fields shouldn't be updated).
Then I change a specific field and press save.

How to update the record, not touching the fields that are not in form?

like image 563
lvil Avatar asked Apr 23 '12 06:04

lvil


People also ask

What is ActiveRecord in Yii2?

ActiveRecord is the base class for classes representing relational data in terms of objects. Active Record implements the Active Record design pattern. The premise behind Active Record is that an individual yii\db\ActiveRecord object is associated with a specific row in a database table.

What is ORM in yii?

Yii Query Builder offers an object-oriented method for building SQL queries, which helps reduce risk of SQL injection attacks. And Yii Active Record (AR), implemented as a widely adopted Object-Relational Mapping (ORM) approach, further simplifies database programming.

What is active query in Yii2?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.


1 Answers

The approach pointed out by mazzucci is more complicated than necessary. Try this:

YourTable::model()->updateByPk($id, array(
    'field1' => NewVal1,
    'field2' => NewVal2,
    'field3' => NewVal3
));
like image 99
Andy Avatar answered Nov 15 '22 14:11

Andy