Saturday, March 19, 2016

Kết nối database và sử dụng Active record trong model 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
2
3
4
5
6
7
'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=yii2adv',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],

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
2
3
4
5
6
7
8
9
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `fullname` varchar(100) NOT NULL,
  `gender` tinyint(4) NOT NULL DEFAULT '1',
  `email` varchar(100) NOT NULL,
  `status` tinyint(4) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Tạo file common\models\users.php với nội dung
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
 
namespace common\models;
 
use Yii;
 
 
class Users extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'users';
    }
 
    public function rules()
    {
        return [
            [['username', 'password', 'fullname', 'email'], 'required'],
            [['gender', 'status'], 'integer'],
            [['username', 'password', 'fullname', 'email'], 'string', 'max' => 100]
        ];
    }
}

- \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
3
4
5
6
7
8
9
10
11
12
13
/**
* description get list users
* Author Ha Tuan Kiet(haanhdon@gmail.com)
* Date 12/02/2016
*/
public function getListUsers()
{
    $query = new \yii\db\Query();
    $query->select('*')
            ->from(self::tableName())
            ->limit(10);
    return $query->createCommand()->queryAll();
}

Trong controller khởi tạo model users , Lấy thông tin users và truyền qua view
1
2
3
4
5
//Khởi tạo model
$model = new \common\models\Users();
$listUsers = $model->getListUsers();
         
return $this->render('index',['listUsers' => $listUsers]);

Controller users : frontend\controllers\UsersController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
 
namespace frontend\controllers;
 
use Yii;
use yii\web\Controller;
 
Class UsersController extends Controller
{
    public function actionIndex()
    {
        Yii::$app->view->title = 'Thao tác với model - Yii2 Framework';
         
        //Khởi tạo model
        $model = new \common\models\Users();
        $listUsers = $model->getListUsers();
         
        return $this->render('index',['listUsers' => $listUsers]);
    }
}


Ở view ta chỉ cần lặp đổ list users là xong
1
http://yiiadvanced/users

Để xem chi tiết hơn bạn hãy xem video dưới đây :






Chúc các bạn thành công


No comments:

Post a Comment