当前位置:Gxlcms > php框架 > Laravel框架学习笔记(二)项目实战之模型(Models)

Laravel框架学习笔记(二)项目实战之模型(Models)

时间:2021-07-01 10:21:17 帮助过:20人阅读

在开发mvc项目时,models都是第一步。

下面就从建模开始。

1.实体关系图,

由于不知道php有什么好的建模工具,这里我用的vs ado.net实体模型数据建模

下面开始laravel编码,编码之前首先得配置数据库连接,在app/config/database.php文件

  1. 'mysql' => array(
  2. 'driver' => 'mysql',
  3. 'read' => array(
  4. 'host' => '127.0.0.1:3306',
  5. ),
  6. 'write' => array(
  7. 'host' => '127.0.0.1:3306'
  8. ),
  9. 'database' => 'test',
  10. 'username' => 'root',
  11. 'password' => 'root',
  12. 'charset' => 'utf8',
  13. 'collation' => 'utf8_unicode_ci',
  14. 'prefix' => '',
  15. ),

配置好之后,需要用到artisan工具,这是一个php命令工具在laravel目录中

首先需要要通过artisan建立一个迁移 migrate ,这点和asp.net mvc几乎是一模一样

在laravel目录中 shfit+右键打开命令窗口 输入artisan migrate:make create_XXXX会在app/database/migrations文件下生成一个带时间戳前缀的迁移文件

代码:

  1. <?php
  2. use Illuminate\Database\Schema\Blueprint;
  3. use Illuminate\Database\Migrations\Migration;
  4. class CreateTablenameTable extends Migration {
  5. /**
  6. * Run the migrations.
  7. *
  8. * @return void
  9. */
  10. public function up()
  11. {
  12. }
  13. /**
  14. * Reverse the migrations.
  15. *
  16. * @return void
  17. */
  18. public function down()
  19. {
  20. }
  21. }

看到这里有entityframework 迁移经验的基本上发现这是出奇的相似啊。

接下来就是创建我们的实体结构,laravel 的结构生成器可以参考http://v4.golaravel.com/docs/4.1/schema

  1. <?php
  2. use Illuminate\Database\Schema\Blueprint;
  3. use Illuminate\Database\Migrations\Migration;
  4. class CreateTablenameTable extends Migration {
  5. /**
  6. * Run the migrations.
  7. *
  8. * @return void
  9. */
  10. public function up()
  11. {
  12. Schema::create('posts', function(Blueprint $table) {
  13. $table->increments('id');
  14. $table->unsignedInteger('user_id');
  15. $table->string('title');
  16. $table->string('read_more');
  17. $table->text('content');
  18. $table->unsignedInteger('comment_count');
  19. $table->timestamps();
  20. });
  21. Schema::create('comments', function(Blueprint $table) {
  22. $table->increments('id');
  23. $table->unsignedInteger('post_id');
  24. $table->string('commenter');
  25. $table->string('email');
  26. $table->text('comment');
  27. $table->boolean('approved');
  28. $table->timestamps();
  29. });
  30. Schema::table('users', function (Blueprint $table) {
  31. $table->create();
  32. $table->increments('id');
  33. $table->string('username');
  34. $table->string('password');
  35. $table->string('email');
  36. $table->string('remember_token', 100)->nullable();
  37. $table->timestamps();
  38. });
  39. }
  40. /**
  41. * Reverse the migrations.
  42. *
  43. * @return void
  44. */
  45. public function down()
  46. {
  47. Schema::drop('posts');
  48. Schema::drop('comments');
  49. Schema::drop('users');
  50. }
  51. }

继续在上面的命令窗口输入php artisan migrate 将执行迁移

更多迁移相关知识:http://v4.golaravel.com/docs/4.1/migrations

先写到这里明天继续

人气教程排行