How to create Model in Yii2 using Gii tool

Posted by in Yii 2

First of all, you should install yii2 to follow these steps.

After installation, you can then access Gii tool through the following URL:

[eg: http://localhost/yii2advanced/frontend/web/index.php?r=gii]

If you have enabled pretty URLs, you may use the following URL:

[eg: http://localhost/yii2advanced/frontend/web/index.php/gii]

possible errors: Page Not Found, Unable to resolve the request gii
solution: check whether the gii module is enabled in @app/frontend/config/main-local.php


Installing Gii Tool

Installing Gii Tool

Model Generator

This generator generates an ActiveRecord class for the specified database table.

Click “start” button under model generator to create Models.

Before that, create table in your database, for example

Table Name – This is the name of the DB table that the new ActiveRecord class is associated with.

Type 'products' in Table Name field

Model Class – This is the name of the ActiveRecord class to be generated.

Type 'Products' (starts with capital letter) in Model Class

Namespace – This is the namespace of the ActiveRecord class to be generated.

By default Namespace is app\models

Base Class – This is the base class of the new ActiveRecord class. It should be a fully qualified namespaced class name.

By default Base Class is yii\db\ActiveRecord

Database Connection ID – This is the ID of the DB application component.

By default Database Connection ID is db

Use Table Prefix – This indicates whether the table name returned by the generated ActiveRecord class should consider the tablePrefix setting of the DB connection.

For example, if the table name is tbl_post, the ActiveRecord class will return the table name as {{%post}}.

Generate relations – This indicates whether the generator should generate relations based on foreign key constraints it detects in the database.

Note: that if your database contains too many tables, you may want to uncheck this option to accelerate the code generation process.

Generate Labels from DB Comments – This indicates whether the generator should generate attribute labels by using the comments of the corresponding DB columns.

Enable I18N – Set this to true if you are planning to make your application translate into many languages.

Message Category – This category is used, if you enable I18N.

Code Template – Please select which set of the templates should be used to generated the code.

Then Click “Preview” button, it will show the path of the code file. If you already created this Model and you want to overwrite it. Check the overwrite check box.

Then click “Generate” button to generate the files and your Model files is generated in @app\frontend\models\

Create Model Using Gii

Create Model Using Gii

Share your comments