PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

PHP中文网
PHP中文网 原创
2016-07-13 10:17:14 1078浏览

上一篇已经介绍开发环境的搭建,这篇将从项目实战开发,一步一步了解laravel框架。首先我们来了解下laravel框架的模型 (Models)

在开发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://www.php.cn/

<?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(&#39;posts&#39;, function(Blueprint $table) {
   $table->increments(&#39;id&#39;);
   $table->unsignedInteger(&#39;user_id&#39;);
   $table->string(&#39;title&#39;);
   $table->string(&#39;read_more&#39;);
   $table->text(&#39;content&#39;);
   $table->unsignedInteger(&#39;comment_count&#39;);
   $table->timestamps();
  });

  Schema::create(&#39;comments&#39;, function(Blueprint $table) {
   $table->increments(&#39;id&#39;);
   $table->unsignedInteger(&#39;post_id&#39;);
   $table->string(&#39;commenter&#39;);
   $table->string(&#39;email&#39;);
   $table->text(&#39;comment&#39;);
   $table->boolean(&#39;approved&#39;);
   $table->timestamps();
  });

   Schema::table(&#39;users&#39;, function (Blueprint $table) {
   $table->create();
   $table->increments(&#39;id&#39;);
   $table->string(&#39;username&#39;);
   $table->string(&#39;password&#39;);
   $table->string(&#39;email&#39;);
   $table->string(&#39;remember_token&#39;, 100)->nullable();
   $table->timestamps();
  });
 }

 /**
  * Reverse the migrations.
  *
  * @return void
  */
 public function down()
 {
  Schema::drop(&#39;posts&#39;);

  Schema::drop(&#39;comments&#39;);

  Schema::drop(&#39;users&#39;);
 }

}

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。