Saturday, March 19, 2016

Tạo CRUD trong Gii với Yii 2 framework

Trong bài này mình xin hướng dẫn đến các bạn CRUD trong Gii với Yii 2 frameworkCác bạn gọi đến đường dẫn sau đây: http://yii2advanded/backend/web/index.php?r=gii
Tạo bảng posts với các trường như sau:
yii2_1
Tạo quan hệ cho author_id với user_id ở bảng user ở bài trước bằng cách vào bảng posts click relation view
yii2_2
Xuống author_id chọn như trong ảnh:
yii2_3
Ta được quan hệ của 2 bảng như hình sau:
yii2_4
vào đường dẫn: http://yii2advanded/backend/web/index.php?r=gii để tạo module cho bảng posts:
yii2_5
Vào CRUD Generator để tạo các file Controller, View cho bảng posts với model là Posts vừa tạo nhé:
yii2_6

Kết quả đạt được sau khi tạo là:
yii2_7
Như vậy là bạn đã tạo thành công giờ bạn có thể tạo bài viết, update, view với bảng Posts rồi. Truy cập vào http://yii2advaned/backend/web/index.php?r=posts để test nhé.
Để xem chi tiết hơn mời các bạn xem video dưới đây 


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

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