Sobes.tech
Junior — Middle

Explain the concept of Active Record in Yii2 and how it is used when interacting with a database.

sobes.tech AI

Answer from AI

Active Record in Yii2 is a pattern for working with a database, where each model represents a single table, and a model object corresponds to one record in that table. The model contains methods for reading, writing, updating, and deleting data.

Example of usage:

// Retrieving a record with id=1
$user = User::findOne(1);

// Changing a property and saving
$user->name = 'Ivan';
$user->save();

// Creating a new record
$newUser = new User();
$newUser->name = 'Maria';
$newUser->email = 'maria@example.com';
$newUser->save();

Thus, Active Record simplifies working with the database by allowing data manipulation through objects without manually writing SQL queries.