The previous article we took a Yii2 MVC
, Forms
and Layouts
, this article directly according to the agreement to say YII2 related to the database some things, if you feel enough, not anxious, more specific usage I will in the follow-up tutorial given, The YII2 code generation tool is also described here: powerful Gii
.
You can download the project directly to GitHub Source: https://github.com/JellyBool/helloYii, so you can directly follow my progress, every time I finish a tutorial, I will push the code to GitHub, so, If you want to be lazy, this is a good way.
Then the previous article, we have not changed the original intention: to create a published state (status)
of the Web small application, you can be seen as the QQ space to say the mini version, but we did not have the data in the database.
Create a database
Since my usual development is basically using MySQL, and database management tools I prefer sequel Pro, so I will directly in the sequel Pro Create a hello
database. Of course, you can also create a database directly from the command line, presumably:
CREATE DATABASE hello;
With the database, we can connect our Yii application with the database, YII2 database configuration file is located /config/db.php
, we can open it for the corresponding configuration, please pay attention to the corresponding changes according to their actual situation:
<?phpreturn [ ‘class‘ => ‘yii\db\Connection‘, ‘dsn‘ => ‘mysql:host=localhost;dbname=hello‘, ‘username‘ => ‘root‘, ‘password‘ => ‘password‘, ‘charset‘ => ‘utf8‘,];
Create migration
This word is used directly here migration
, in fact I do not know what to translate into what is more accurate, so this article directly use the migration
Word, if you know there is a particularly appropriate translation, please speak to me loudly. migration
The biggest goal may be to create a data table, but why should we use it migration
? This may be affected by Rails
the DAFA, because this is actually a lot of benefits, migration
not only allows developers to dynamically create and update a database table schema, but also can deal with multiple servers when the environment of different problems, directly avoid the import of SQL files of various pits.
As for how we should name our data table in the code, what I prefer is that it is just like model, and if it is a single complex problem it doesn't matter, this looks personal, so here I would choose to create a status
table, iterm command line execution:
cd Desktop/helloYii/./yii migrate/create create_status_table
The process will ask whether to create migration
, be decisive yes
, and then complete the following is probably the case:
This command creates a directory under the project directory with the migrations/
migration file that we just created, which is probably the name: and m150804_035107_create_status_table.php
then we can open this file to see hosting:
<?phpUseYii\Db\Schema;use yii\db\ migration; class m150804_035107_create_status _table extends migration{public Span class= "hljs-function" >function up () {} public function down () { echo "m150804_035107_create_status_table cannot be reverted.\n"; return false;}
Well, that's probably the case, the up()
method is ./yii migrate/up
triggered when we execute the command, which is usually responsible for creating a table, and we can write the table schema
in this method.
Create a status table
With the above migration, we can up()
write some of our fields and configurations directly in the method:
PublicfunctionUp() {$tableOptions =Nullif ($this->db->drivername = = =' MySQL ') {$tableOptions =' CHARACTER SET UTF8 COLLATE utf8_unicode_ci engine=innodb '; }$this->createtable ( ' {{%status}} ', [ ' id ' = SCHEMA::TYPE_PK, ' message ' = Schema::type_text. "not NULL DEFAULT" "', ' permissions ' = Schema::type_smallint . "not NULL DEFAULT 0 ', ' created_at ' = Schema::type_integer. Span class= "hljs-string" > ' not NULL ', ' updated_at ' = Schema::type_integer. ' not NULL ',], $tableOptions); } public function down () { $this->droptable (
Here we status
will have 5 fields, the id
primary key, message
and that is the content of the text content and drop-down permissions
selection box entered in our text input box; Here we have two created_at
and updated_at
fields, and, uh, you can say I was brainwashed by a laravel.
down()
Method and up()
corresponding, used to delete the data table, I hope you will not use.
More detailed information is here:
Http://www.yiiframework.com/doc-2.0/guide-db-migrations.html
With the table schema
, we can execute our migrate command, which is executed by the command line:
./yii migrate/up
Process is decisive yes
, and then you can go to the hello
database to see status
the table:
Here you will also see a migration
table, this is YII2 migrate auto-generated, it is used to manage our own created migration
(here refers to the data table), you can not care about it.
Once you've created the datasheet using Yii2 's migrate, let's get started with the YII2 Code generation tool, which we'll use to generate our model and controller files.
Use the GII
GII as a major feature of Yii, many people like Yii probably because of this, it is said that the underlying code is very good, but I have not read the source carefully.
Let's start by using the GII to generate a model for each data table, which is where the status is generated.
How to access the GII panel? Enter the access directly in the browser's address bar http://localhost:8999/gii
. This is probably the way it looks:
Click on the Model Generator button and fill in the Table Name
table name in the input box:status
Click on the preview button below to see the files that Yii is going to help you build models/Status.php
, and here's a place to be aware of. Since we created a status model manually in the previous article, make sure you Overwrite
gogo the small selection box:
Then click on the Generate button to generate the result:
At this point models/Status.php
, you will see the validation rules and form attributes that Yii generates based on our data tables:
<?phpNamespaceApp\ModelsUseYii;/** * This is the Model class for table "status". * *@property Integer $id *@property String $message *@property Integer $permissions *@property integer $created _at *@property integer $updated _at */ClassStatusExtends \Yii\Db\activerecord{/** *@inheritdoc */PublicStaticfunctionTableName() {Return' Status '; }/** *@inheritdoc */PublicfunctionRules() {return [[[' Message ',' Created_at ',' Updated_at '],' Required '], [[' Message ',' String '], [[' Permissions ', ' Created_at ', ' Updated_at '], Integer ']]; } /** * @inheritdoc */public function attributelabels () {return [ ' id ' = = ' ID ', ' message ' = ' message ', Span class= "hljs-string" > ' permissions ' + ' permissions ', Created_at ' + ' created at ', ' updated_at ' +
When the status model is generated, it is time to generate the appropriate view and controller for it, which is what we need to use for the GII CRUD Generator
, namely:http://localhost:8999/gii/crud
On this page, fill in the respective data:
Model Class : app\models\StatusSearch Model Class : app\models\StatusSearchController Class : app\controllers\StatusControllerView Path : 可以直接留空,默认就是 app/views/ControllerID
Then click on Preview, here still need to overwrite
check, because we also created in the previous section two of the same name of the view file (create.php 和 view.php)
:
Finally, click Generate, and you'll see something like this:
When we get here, we can basically feel the power of the GII, and generating code is nothing. At this time, if we visit http://localhost:8999/status
, you will see a default status of the Crud page, because our database does not have any data, so what we see here is empty:
If you remember the navigation that we created in the navigation bar on the previous create
page, click on it create
and you'll see something like this:
Do you feel that the GII is too powerful to be here? If we were to generate the code directly from the GII, the development efficiency was not generally high.
The combination with the previous article
Although the GII is strong enough for us to generate a lot of code, there is now a small piece of code that doesn't meet our requirements and we don't have to be so complicated. So let's go through the code first so that it can be used to meet our own requirements.
The first is to transform the form that created the status, and we don't want the user to have to enter created
and both updated
fields, so comment out /views/Status/_form.php
the following code:
<?= $form->field($model, ‘created_at‘)->textInput() ?><?= $form->field($model, ‘updated_at‘)->textInput() ?>
Then permissions
field input We want this to be a drop-down selection box or to be modified in the same file:
<?= $form->field($model, ‘permissions‘)->dropDownList($model->getPermissions(), [‘prompt‘=>‘- Choose Your Permissions -‘]) ?>
We've replaced the original with the permissions
textInput
one above, which is dropDownList
dropDownList
used here getPermissions()
, but because we've covered the status of forgiveness since we just generated the status model, we still need to add getPermissions()
this method:
Const PERMISSIONS_PRIVATE =10;Const PERMISSIONS_PUBLIC =20;Other codes ...PublicfunctionGetPermissions () {return array (self::P ermissions_private=> ' PRIVATE ', Self::P ermissions_public=>public function getpermissionslabel ( $permissions) {if ( $permissions ==self::P ermissions_ Public) {return else {return ' Private ';}}
As mentioned in the previous article, we have written this code again Status.php
here. Then refresh:http://localhost:8999/status/create
Here, our form makeover was done, and it was almost as long as we had before. But this is not over, because we also need to controllers/StatusController.php
do some minor changes to our, mainly in actionCreate
the changes:
PublicfunctionActioncreate () { $model = new Status (); if ( $model->load (yii:: $app- Request->post ())) { $model->created_at = time (); $model->updated_at = time (); if ( $model->save ()) {return $this->redirect ([ ' view ', ' ID ' = = $model->id]); }} return $this->render ( Create ', [ ' model ' = $model,]);}
Here, we add the following two lines to ensure that we are inserting data, created_at
and updated_at
not empty.
$model->created_at = time();$model->updated_at = time();
This is also based on $model->load(Yii::$app->request->post())
judging if there is post data coming up, and then if the data is successfully saved to the database, we use return $this->redirect([‘view‘, ‘id‘ => $model->id])
redirection to the view
method (controllers/StatusController.php的actionView方法)
. We fill in some data and then create a status to try, not surprisingly you will see this lovely page:
It's finally here, we're going to change our navigation now, in the status this down menu, we add a menu view, modify views/layouts/main.php
the part of the file Nav::widget
:
[ ‘label‘ => ‘Status‘, ‘items‘ => [ [‘label‘ => ‘View‘, ‘url‘ => [‘/status/index‘]], [‘label‘ => ‘Create‘, ‘url‘ => [‘/status/create‘]], ],],
Add a line directly to the status items: and [‘label‘ => ‘View‘, ‘url‘ => [‘/status/index‘]]
then our navigation bar is like this:
Click on the drop-down menu of view, then we will come to: http://localhost:8999/status/index
, here we can see the following page:
This view file is located views/status/index.php
, if you want to modify it, you can directly modify this file.
Ah, I feel this article is a long way to go, but in fact, the actual encoding time is not too much, really may be just a few minutes, we have achieved some basic operation of the database and appreciate the strong gii. This article is first written here, the next one is going to write a little about the user registration and login basic functions.
The source will be placed in Github:https://github.com/jellybool/helloyii
YII2 Series Tutorial Three: Database and Gii