首页 > 代码库 > laravel 连接建立数据库

laravel 连接建立数据库

1、框架设置

 首先我们需要设置一下laravel框架,打开application/config/application.php文件,我们要先把文件中的key参数设置为任意的32位字符串:

  1. ‘key‘=>‘YourSecretKeyGoesHere!‘,
  2.  

这个字符串会被用于加密我们的密码。然后在application/config/database.php中设置数据库信息,其中database是我们事先建立的,你可以随意命名:

  1. ‘mysql‘=>array(
  2.        ‘driver‘ =>‘mysql‘,
  3.        ‘host‘   =>‘localhost‘,
  4.        ‘database‘=>‘database‘,
  5.        ‘username‘=>‘root‘,
  6.        ‘password‘=>‘123456‘,
  7.        ‘charset‘ =>‘utf8‘,
  8.        ‘prefix‘ =>‘‘,
  9.        ),
  10. 2、创建数据库
  11. 然后我们将使用Artisan和Migrations工具来建立数据库,你可以简单的把它理解为一个数据库工具,在使用它之前我们需要初始化它。先把你的php目录加入到系统的环境变量中,然后打开cmd工具cd到web的根目录运行命令:

    1. php artisan migrate:install
    2.  

    这是我们进入database数据库发现里面多了一张名为laravel_migrations的表,它记录了migrate需要的数据。然后我们运行下面的两条命令:

    1. php artisan migrate:make create_admin_table
    2. php artisan migrate:make create_docs_table
    3.  

    运行成功之后我们可以在application/migrations目录看到名为日期_creat_admin_table.php和日期_creat_docs_table.php两个文件。

    先打开creat_admin_table.php文件,在up和down方法中添加代码:

    1. publicfunctionup()
    2. {
    3.    Schema::create(‘admin‘,function($table)
    4.    {
    5.         $table->increments(‘id‘);
    6.         $table->string(‘email‘,64);
    7.         $table->string(‘password‘,64);
    8.      });
    9.      DB::table(‘admin‘)->insert(array(
    10.                        ‘email‘=>‘your email‘,
    11.                        ‘password‘=>Hash::make(‘your password‘),
    12.                    ));
    13. }
    14. publicfunctiondown()
    15. {
    16.    Schema::drop(‘admin‘);
    17. }
    18.  

    再编辑creat_docs_table.php文件:

    1. publicfunctionup()
    2. {
    3.    Schema::create(‘docs‘,function($table)
    4.    {
    5.         $table->increments(‘id‘);
    6.         $table->string(‘title‘,64);
    7.         $table->text(‘content‘);
    8.         $table->string(‘create_date‘,12);
    9.         $table->string(‘last_change‘,12);
    10.    });
    11.      DB::table(‘docs‘)->insert(array(
    12.                        ‘title‘=>‘test‘,
    13.                        ‘content‘=>‘just a test!‘,
    14.    ‘create_date‘=>time(),
    15.                        ‘last_change‘=>‘‘
    16.                     ));
    17. }
    18. publicfunctiondown()
    19. {
    20.    Schema::drop(‘docs‘);
    21. }
    22.  
    23. 保存完毕之后我们继续运行命令:php artisan migrate

    24. 数据库建立完成


laravel 连接建立数据库