You are on page 1of 8

Thao tác với cơ sở dữ liệu thông qua Model trong Yii 2

Framework
Yii2 Framework thực hiện các xử lý với cơ sở dữ liệu thông qua Model. Ở phần trước ta đã cấu hình
kết nối với cơ sở dữ liệu. Ở phần này ta sẽ tìm hiểu về các truy vấn xử lý với database trong model.

Bây giờ trong database study_yii2 ta có một table như sau:

CREATE TABLE IF NOT EXISTS `products` (

`product_id` int(11) NOT NULL AUTO_INCREMENT,

`product_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,

`price` varchar(32) COLLATE utf8_unicode_ci NOT NULL,

`number` int(11) NOT NULL,

`category_id` int(11) NOT NULL,

`status` tinyint(1) NOT NULL DEFAULT '1',

PRIMARY KEY (`product_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Trong Yii2 có hỗ trợ một công cụ là Gii giúp tạo nhanh các thành phần như: Model, Form, Controller,
Module... Để tạo nhanh model ta vào đường dẫn http://study-yii2/gii

Trong mục Model Generator ấn Start


Tiếp đến trong phần Table Name ghi tên table cần tạo model, trong phần Model Class sẽ hiện tên
class của Model. Ấn nút Preview rồi sau đó ấn Generate.
Lúc này trong thư mục model của project, ta có một file tên Products.php có cấu trúc như sau

<?php

namespace app\models;
use Yii;

/**

* This is the model class for table "products".

* @property integer $product_id

* @property string $product_name

* @property string $price

* @property integer $number

* @property integer $category_id

* @property integer $status

*/

class Products extends \yii\db\ActiveRecord

/**

* @inheritdoc

*/

public static function tableName()

return 'products';

/**

* @inheritdoc

*/

public function rules()

return [
[['product_name', 'price', 'number', 'category_id'], 'required'],

[['number', 'category_id', 'status'], 'integer'],

[['product_name'], 'string', 'max' => 100],

[['price'], 'string', 'max' => 32],

];

/**

* @inheritdoc

*/

public function attributeLabels()

return [

'product_id' => 'Product ID',

'product_name' => 'Product Name',

'price' => 'Price',

'number' => 'Number',

'category_id' => 'Category ID',

'status' => 'Status',

];

Trong đó:

 Class Products kế thừa thư viện \yii\db\ActiveRecord của yii2.


 Function tableName() trả về tên của table.
 Function rules() sử dụng để khai báo các trường và các quy định dùng cho validate dữ liệu.
 Function attributeLabels() để hiển thị tên label khi sử dụng các trường.

Bây giờ trong model ta tạo một function getProducts() để lấy toàn bộ data của bảng products

public function getProducts()


{

$products = self::find()->all();

return $products;

Tiếp đến ta tạo một controller Product, sau đó trong controller khởi tạo model Products và gọi đến
hàm getProducts() 

<?php

namespace app\controllers;

use Yii;

use yii\web\Controller;

use app\models\Products;

class ProductController extends Controller

public function actionIndex()

$model = new Products(); // khởi tạo model

$products = $model->getProducts(); // gọi đến hàm getProducts()

$productLabels = $model->attributeLabels(); // gọi đến hàm attributeLabels


để lấy label

// Đổ vào view

return $this->render('index',[

'products' => $products,

'label' => $productLabels,

]);

}
?>

Bên view ta chỉ cần chạy lặp để lấy dữ liệu

<div class="table-responsive">

<table class="table table-hover">

<thead>

<tr>

<th><?=$label['product_id']?></th>

<th><?=$label['product_name']?></th>

<th><?=$label['price']?></th>

<th><?=$label['number']?></th>

<th><?=$label['category_id']?></th>

<th><?=$label['status']?></th>

</tr>

</thead>

<tbody>

<?php foreach ($products as $product): ?>

<tr>

<td><?=$product->product_id?></td>

<td><?=$product->product_name?></td>

<td><?=$product->price?></td>

<td><?=$product->number?></td>

<td><?=$product->category_id?></td>

<td><?=$product->status?></td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>
Ở bài viết này, chúng ta đã tìm hiểu sơ lược về chức năng cũng như cách hoạt động của model với
database. Ở phần sau chúng ta sẽ tìm hiểu sâu hơn về model. 

* Bài viết được viết theo những gì mình hiểu nên có thể sẽ khó hiểu với những ai đọc. Nếu có bất cứ
thắc mắc hoặc đóng góp cho bài viết được hoàn thiện hơn thì hãy để lại bình luận phía dưới nhé!

You might also like