08 YiiModel

You might also like

You are on page 1of 5

Yii2 phần 4 - Thao tác với models trong yii2 framework

Thao tác với model trong Yii2 Framework, chúng ta sẽ tìm hiểu các kết nối database, các phương thức truy vấn,
query với database như thế nào

Yii2 là một framework nổi tiếng được cộng đồng sử dụng rộng rãi, các phương thức truy vấn database tương đối
nhiều, chúng ta sẽ đi tìm hiểu một số phương thức chính, hay được sử dụng nhất. Trước tiên thao tác với database
thì ta cần phải kết nối cơ sở dữ liệu.

1. Kết nối với database


Mở file common\config\main-local.php điền thông tin database của bạn vào

1 'db' => [

2             'class' => 'yii\db\Connection',

3             'dsn' => 'mysql:host=localhost;dbname=yii2adv',

4             'username' => 'root',

5             'password' => '',

            'charset' => 'utf8',


6
        ],
7

2. Thao tác với model


Trong Yii2 Framework model được đặt ở 3 folder bao gồm

- common\models : đây là phần model chung cho cả frontend và backend, đây cũng là nơi sẽ chứa các model chính
mà mình hay sử dụng
- frontend\models : model riêng cho frontend
- backend\models : model riêng cho backend

Trong các dự án thì ta hay sử dụng common\models nhất, vì frontend và backend thường dùng chung một model khi
thao tác với database

Tạo model, cú pháp một model trong Yii2

Trong database yii2adv ta có bảng users

1 CREATE TABLE IF NOT EXISTS `users` (

`id` int(11) unsigned NOT NULL,


2
  `username` varchar(100) NOT NULL,
3
  `password` varchar(100) NOT NULL,
4
  `fullname` varchar(100) NOT NULL,
5
  `gender` tinyint(4) NOT NULL DEFAULT '1',
6
  `email` varchar(100) NOT NULL,
7
  `status` tinyint(4) NOT NULL DEFAULT '1'
8
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9

Tạo file common\models\users.php với nội dung

1 <?php

2  
namespace common\models;
3

4  
use Yii;
5
 
6
 
7
class Users extends \yii\db\ActiveRecord
8
{
9
    public static function tableName()
10
    {
11         return 'users';

12     }

13  
14     public function rules()

15     {

        return [
16
            [['username', 'password', 'fullname', 'email'],
17 'required'],

18             [['gender', 'status'], 'integer'],

            [['username', 'password', 'fullname', 'email'], 'string',


19
'max' => 100]
20
        ];
21
    }
22
}
23

- \yii\db\ActiveRecord là thư viện activerecord của Yii2


- function tableName() trả về tên của table trong database
- function rules() khai báo các trường của table users, được dùng cho phần validate

Tạo function getListUsers() trong model users để lấy thông tin từ database

1
/**
2
* description get list users
3
* Author Ha Tuan Kiet(haanhdon@gmail.com)
4
* Date 12/02/2016
5 */

6 public function getListUsers()

7 {

8     $query = new \yii\db\Query();

    $query->select('*')
9
            ->from(self::tableName())
10
            ->limit(10);
11
    return $query->createCommand()->queryAll();
12
}
13

Trong controller khởi tạo model users , Lấy thông tin users và truyền qua view

1 //Khởi tạo model

$model = new \common\models\Users();


2
3 $listUsers = $model->getListUsers();

4          

5 return $this->render('index',['listUsers' => $listUsers]);

Controller users : frontend\controllers\UsersController.php

1 <?php

2  
3 namespace frontend\controllers;

4  

5 use Yii;

6 use yii\web\Controller;

7  
Class UsersController extends Controller
8
{
9
    public function actionIndex()
10
    {
11
        Yii::$app->view->title = 'Thao tác với model - Yii2
12 Framework';

13          

        //Khởi tạo model


14
        $model = new \common\models\Users();
15
        $listUsers = $model->getListUsers();
16
         
17
        return $this->render('index',['listUsers' =>
18 $listUsers]);

19     }

}
20
Ở view ta chỉ cần lặp đổ list users là xong

1 http://yiiadvanced/users

Có rất nhiều phương thức active record trong Yii2 framework, Ở bài này chúng ta mới chỉ làm quen với model, bài
sau chúng ta sẽ đi tìm hiểu sâu hơn về model trong Yii2

You might also like