Birmingham mumbai


Building the database schema


Download 1.3 Mb.
Pdf ko'rish
bet62/68
Sana05.01.2022
Hajmi1.3 Mb.
#227543
1   ...   58   59   60   61   62   63   64   65   ...   68
Bog'liq
Laravel 5 Essentials

Building the database schema

Now that we have defined our models, we need to create the corresponding database 

schema. Thanks to Laravel's support for migrations and its powerful schema builder

you will not have to write any SQL code and you will also be able to keep track of 

any schema changes in a version control system. To create your first migration, open 

a new terminal window and enter the following command:



$ php artisan make:migration create_breeds_table --create=breeds


Chapter 3

[

 31 

]

This will create a new migration at 

database/migrations/

. If you open the newly 

created file, you will find some code that Laravel has generated for you. Migrations 

always have an 

up()

 and 


down()

 method that defines the schema changes when 

migrating up or down. Migrating up is modifying the database schema (that is, adding 

a table at a later date), whereas, migrating down is the process of undoing that schema 

change. By convention, the table and field names are written in snake_case. Also, the 

table names are written in plural form.

Our 

breeds


 table migration will look like this:

  public function up() {

    Schema::create('breeds', function($table) {

      $table->increments('id');

      $table->string('name');

    });


  }

  public function down() {

    Schema::drop('breeds');

  }


We can repeat the process to also create our 

cats


 table schema:

public function up() {

  Schema::create('cats', function($table) {

    $table->increments('id');

    $table->string('name');

    $table->date('date_of_birth');

    $table->integer('breed_id')->unsigned()->nullable();

    $table->foreign('breed_id')->references('id')->on('breeds');

  });

}

public function down() {



  Schema::drop('cats');

}

The 



date()

 and 


string()

 methods create fields with the corresponding types 

(in this case

DATE


 and 

VARCHAR


) in the database, 

increments()

 creates an auto-

incrementing 

INTEGER

 primary key, and 

timestamps()

 adds the 

created_at

 and 


updated_at

 

DATETIME



 fields that Eloquent expects, by default. The 

nullable()

 

method specifies that the column can have 



NULL

 values.


www.allitebooks.com


Your First Application


Download 1.3 Mb.

Do'stlaringiz bilan baham:
1   ...   58   59   60   61   62   63   64   65   ...   68




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling