- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
Yii2 Models, Active Record & Database Connections
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:
- Creating and using Active Record models
- Performing CRUD operations
- Setting up database connections
- Using multiple databases in Yii2
- Using different databases for modules
1. Database Connection in Yii2
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).
1.1 Configuring the Database
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',
],
],
2. Creating an Active Record Model
Active Record (AR) allows you to interact with database tables as PHP objects.
2.1 Generating a Model Using Gii
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=gii
Click on Model Generator.
Enter the table name (e.g., users
).
Click Preview, then Generate.
2.2 Manually Creating a Model
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
}
}
3. CRUD Operations with Active Record
3.1 Retrieving Data
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();
3.2 Inserting Data
$user = new User();
$user->username = 'Gourav';
$user->email = 'gourav@example.com';
$user->save();
3.3 Updating Data
$user = User::findOne(1);
$user->email = 'new_email@example.com';
$user->save();
3.4 Deleting Data
$user = User::findOne(1);
$user->delete();
4. Using Multiple Databases in Yii2
Sometimes, you need to connect to multiple databases in Yii2, for example, when dealing with multiple applications.
4.1 Configuring Multiple Databases
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',
];
4.2 Assigning Models to Different Databases
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';
}
}
5. Using Different Databases for Modules
Sometimes, you want each module to use a different database. You can do this by configuring the module’s init()
function.
5.1 Setting Up Module-Specific Database
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',
],
],
];
5.2 Using the Module-Specific Database in Models
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
.
Conclusion
- Yii2 supports multiple databases.
- You can override
getDb()
in models to assign different databases. - Modules can have their own database configuration using
Yii::configure()
.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- How to Start Your Career as a DevOps Engineer
- Top 10 Blogs of Digital Marketing you Must Follow
- AI in Cybersecurity: The Future of Digital Protection
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Exploratory Data Analysis On Iris Dataset
- Avoiding the Beginner’s Trap: Key Python Fundamentals You Shouldn't Skip
- Generative AI - The Future of Artificial Intelligence
- 15 Amazing Keyword Research Tools You Should Explore
- The Ultimate Guide to Data Science: Everything You Need to Know
- Government Datasets from 50 Countries for Machine Learning Training
- Extract RGB Color From a Image Using CV2
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- How to Become a Good Data Scientist ?
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset