In Yii2, models represent data structures and are used for database interactions. Yii2 provides the Active Record (AR) pattern to simplify working with databases by mapping database tables to PHP classes.
In this tutorial, we will cover:
Yii2 uses the db component for database connections. By default, Yii2 stores database configuration in the config/db.php file (for the basic template) or common/config/main.php (for the advanced template).
Modify config/db.php to set up the database connection:
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];For the advanced template, modify common/config/main.php:
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],Active Record (AR) allows you to interact with database tables as PHP objects.
Yii2 provides Gii, a web-based tool to generate models.
Enable Gii in config/web.php:
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1'], // Adjust for remote access
],
],Open Gii in your browser:
http://localhost/yii2-app/index.php?r=giiClick on Model Generator.
Enter the table name (e.g., users).
Click Preview, then Generate.
Alternatively, create a model manually inside the models directory.
For example, create models/User.php:
namespace app\models;
use yii\db\ActiveRecord;
class User extends ActiveRecord
{
public static function tableName()
{
return 'users'; // Table name in the database
}
}Fetch all users:
$users = User::find()->all();Fetch a single user by ID:
$user = User::findOne(1);Find a user by condition:
$user = User::find()->where(['username' => 'admin'])->one();$user = new User();
$user->username = 'Gourav';
$user->email = 'gourav@example.com';
$user->save();$user = User::findOne(1);
$user->email = 'new_email@example.com';
$user->save();$user = User::findOne(1);
$user->delete();Sometimes, you need to connect to multiple databases in Yii2, for example, when dealing with multiple applications.
Modify config/db.php (or common/config/main.php for advanced template):
return [
'components' => [
'db' => require(__DIR__ . '/db-main.php'), // Default database
'db2' => require(__DIR__ . '/db-second.php'), // Second database
],
];Then create separate database configuration files:
config/db-main.php (First Database - Main DB)
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=main_db',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];config/db-second.php (Second Database - Orders DB)
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=orders_db',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];By default, all models use Yii::$app->db. To make a model use another database, override the getDb() method.
For the User model (Main Database):
namespace app\models;
use yii\db\ActiveRecord;
class User extends ActiveRecord
{
public static function getDb()
{
return \Yii::$app->db; // Connects to the main database
}
public static function tableName()
{
return 'users';
}
}For the Orders model (Second Database):
namespace app\models;
use yii\db\ActiveRecord;
class Orders extends ActiveRecord
{
public static function getDb()
{
return \Yii::$app->db2; // Connects to the second database
}
public static function tableName()
{
return 'orders';
}
}Sometimes, you want each module to use a different database. You can do this by configuring the module’s init() function.
Inside the module’s init() method, configure it to load a separate database connection:
Example: modules/dashboard/Module.php
namespace app\modules\dashboard;
use Yii;
use yii\base\Module as BaseModule;
class Module extends BaseModule
{
public function init()
{
parent::init();
Yii::configure($this, require(__DIR__ . '/config/main-local.php'));
}
}Now, create the config/main-local.php file inside the module:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=dashboard_database',
'username' => 'root',
'password' => 'Password#3',
'charset' => 'utf8',
],
],
];Now, inside the Dashboard module models, override getDb() to use the new database:
namespace app\modules\dashboard\models;
use Yii;
use yii\db\ActiveRecord;
class DashboardUser extends ActiveRecord
{
public static function getDb()
{
return Yii::$app->getModule('dashboard')->db;
}
public static function tableName()
{
return 'users';
}
}Now, all models inside the Dashboard module will use the dashboard_database.
getDb() in models to assign different databases.Yii::configure().Sign in to join the discussion and post comments.
Sign in