在開發mvc項目時,models都是第一步。
下面就從建模開始。
1.實體關系圖,
由於不知道php有什麼好的建模工具,這裡我用的vs ado.net實體模型數據建模
下面開始laravel編碼,編碼之前首先得配置數據庫連接,在app/config/database.php文件
'mysql' => array( 'driver' => 'mysql', 'read' => array( 'host' => '127.0.0.1:3306', ), 'write' => array( 'host' => '127.0.0.1:3306' ), 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ),
配置好之後,需要用到artisan工具,這是一個php命令工具在laravel目錄中
首先需要要通過artisan建立一個遷移 migrate ,這點和asp.net mvc幾乎是一模一樣
在laravel目錄中 shfit+右鍵打開命令窗口 輸入artisan migrate:make create_XXXX會在app/database/migrations文件下生成一個帶時間戳前綴的遷移文件
代碼:
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTablenameTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { } /** * Reverse the migrations. * * @return void */ public function down() { } }
看到這裡有entityframework 遷移經驗的基本上發現這是出奇的相似啊。
接下來就是創建我們的實體結構,laravel 的結構生成器可以參考http://v4.golaravel.com/docs/4.1/schema
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTablenameTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->string('title'); $table->string('read_more'); $table->text('content'); $table->unsignedInteger('comment_count'); $table->timestamps(); }); Schema::create('comments', function(Blueprint $table) { $table->increments('id'); $table->unsignedInteger('post_id'); $table->string('commenter'); $table->string('email'); $table->text('comment'); $table->boolean('approved'); $table->timestamps(); }); Schema::table('users', function (Blueprint $table) { $table->create(); $table->increments('id'); $table->string('username'); $table->string('password'); $table->string('email'); $table->string('remember_token', 100)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); Schema::drop('comments'); Schema::drop('users'); } }
繼續在上面的命令窗口輸入php artisan migrate 將執行遷移
更多遷移相關知識:http://v4.golaravel.com/docs/4.1/migrations
先寫到這裡明天繼續