.net转php laraval框架学习系列(二)项目实战---Models
上一篇已经介绍开发环境的搭建,如果有问题可以在文章后留言。
这篇将从项目实战开发,一步一步了解laravel框架。
在开发mvc项目时,models都是第一步。
下面就从建模开始。
实体关系图
由于不知道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文件下生成一个带时间戳前缀的迁移文件,
laravel中的ORM为Eloquent ORM 相关API可以访问http://v4.golaravel.com/docs/4.1/eloquent#inserting-related-models
代码:
<?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
这里已经定义了表和字段,还需要设置表关系,一般外键字段为unsignedInteger 类型。
Post models代码如下
<?php class Post extends Eloquent { protected $fillable = ['title', 'content'];//集体赋值,跟表单绑定有关 public function comments() { return $this->hasMany('Comment');//1对多关系映射 }
public function user() { return $this->belongsTo('User');//1对多关系映射 }
public function delete()//删除联动 { foreach ($this->comments as $comment) { $comment->delete(); } return parent::delete(); } }
comments model 代码
<?php class Comment extends Eloquent { protected $fillable = ['commenter', 'email', 'comment'];//集体赋值,跟表单绑定有关 public function post() { return $this->belongsTo('Post');//依赖对象 } public function getApprovedAttribute($approved)//属性访问器 { return (intval($approved) == 1) ? 'yes' : 'no'; } public function setApprovedAttribute($approved) { $this->attributes['approved'] = ($approved === 'yes') ? 1 : 0; } }
User model代码
<?php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; class User extends Eloquent implements UserInterface, RemindableInterface { /** * 数据库中对应的表名. * * @var string */ protected $table = 'users'; /** * 在JSON格式化中,会自动隐藏的字段. * * @var array */ protected $hidden = array('password'); public function posts() { return $this->hasMany('Post'); } /** * 属性访问器返回主键值 * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * 属性访问器. * * @return string */ public function getAuthPassword() { return $this->password; } /** * 属性访问器. * * @return string */ public function getReminderEmail() { return $this->email; } /** * 属性访问器 * */ public function getRememberToken() { return $this->remember_token; } public function setRememberToken($value) { $this->remember_token = $value; } public function getRememberTokenName() { return 'remember_token'; } }
所有模型都建立完毕接下来需要填充原始数据
填充原始数据在app/database/seeds文件下的DatabaseSeeder.php文件中的run方法中执行。
这里为了方便贴代码就整合到DatabaseSeeder中了
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * 'composer dump-autoload'slove ex * * * @return void */ public function run() { Eloquent::unguard();//数据填充不需要担心之前设置的集体赋值的字段 /* $this->call('UserTableSeeder');//调用其他seeder类的run方法 $this->call('PostCommentSeeder'); */ $content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'. 'Praesent vel ligula scelerisque, vehicula dui eu, fermentum velit.'. 'Phasellus ac ornare eros, quis malesuada augue. Nunc ac nibh at mauris dapibus fermentum.'. 'In in aliquet nisi, ut scelerisque arcu. Integer tempor, nunc ac lacinia cursus, '. 'mauris justo volutpat elit, '. 'eget accumsan nulla nisi ut nisi. Etiam non convallis ligula. Nulla urna augue, '. 'dignissim ac semper in, ornare ac mauris. Duis nec felis mauris.'; $user=new User; $user->username = 'admin'; $user->password = Hash::make('admin'); $user->email = 'admin@admin.com'; $user->save(); for( $i = 1 ; $i <= 20 ; $i++ ) { $post = new Post; $post->title = "Post no $i"; $post->read_more = substr($content, 0, 120); $post->content = $content; $user->posts()->save($post); $maxComments = mt_rand(3,15); for( $j = 1 ; $j <= $maxComments; $j++) { $comment = new Comment; $comment->commenter = 'xyz'; $comment->comment = substr($content, 0, 120); $comment->email = 'xyz@xmail.com'; $comment->approved = 'yes'; $post->comments()->save($comment); $post->increment('comment_count'); } } } }
在命令窗口中运行 php artisan db:seed 将执行数据填充。这一节就到这里了
.net转php laraval框架学习系列(二)项目实战---Models的更多相关文章
- .net转php laraval框架学习系列(一) 环境搭建
之前也没写过什么博客,可能文章结构比较混乱,想到那写到哪. 主要是把自己学习中的经验写下来. 为什么选择laravel框架,是因为laravel框架目前是Php最流行的框架,深入研究后发现和asp.n ...
- .net转php laraval框架学习系列(三)项目实战---Route&Controllers
本章来学习laravel的路由 一个简单的路由列子 Route::get('/', function() { return 'Hello World'; }); 路由的写法和Node的风格很相似.上面 ...
- .net转php laraval框架学习系列(四) 项目实战---View
laravel的参考文档中view的讲解有些简单. 在实际项目开发中view的灵活性其实是非常大. 首先来看看laravel中的布局页 和asp.net mvc中有什么不同 <!DOCTYPE ...
- scrapy爬虫学习系列二:scrapy简单爬虫样例学习
系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备: http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...
- 图机器学习(GML)&图神经网络(GNN)原理和代码实现(前置学习系列二)
项目链接:https://aistudio.baidu.com/aistudio/projectdetail/4990947?contributionType=1 欢迎fork欢迎三连!文章篇幅有限, ...
- MyBatis学习系列二——增删改查
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...
- Maven学习系列二(1-5)
Maven学习系列二(1-5) 本文转自 QuantSeven 博客,讲解精炼易懂,适合入门,链接及截图如下 http://www.cnblogs.com/quanyongan/category/47 ...
- DocX开源WORD操作组件的学习系列二
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参
[转]ASP.NET MVC学习系列(二)-WebAPI请求 传参 本文转自:http://www.cnblogs.com/babycool/p/3922738.html ASP.NET MVC学习系 ...
随机推荐
- Android 常用对话框Dialog封装
Android 6种 常用对话框Dialog封装 包括: 消息对话框.警示(含确认.取消)对话框.单选对话框. 复选对话框.列表对话框.自定义视图(含确认.取消)对话框 分别如下图所示: ...
- PHP Java
http://my.oschina.net/lajp/blog/5121 http://blog.163.com/lijianwei_123/blog/static/18489289120115244 ...
- cf B. Fox Dividing Cheese
http://codeforces.com/contest/371/problem/B #include <cstdio> #include <iostream> #inclu ...
- 读、写SD上的文件请按如下步骤进行
1.调用Environment的getExternalStorageState()方法判断手机上是否插入了SD卡,并且应用程序具有读写SD卡的权限.例如使用如下代码//Environment.getE ...
- BZOJ2091: [Poi2010]The Minima Game
2091: [Poi2010]The Minima Game Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 243 Solved: 163[Subm ...
- UML建模之时序图
现在是二月,而且到如今你或许已经读到.或听到人们谈论UML 2.0 —— 包括若干进步的 UML 的新规范,所做的变化.考虑到新规范的重要性,我们也正在修改这个文章系列的基础,把我们的注意力从 OMG ...
- 面试问题:关于java并发方面的
主要是回答一下面试中可能会碰到的问题.慢慢的积累一下.一个星期以后,补全.
- cf435C Cardiogram
C. Cardiogram time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- github atom创建自己的语法高亮
使用atom一段时间了,有些插件还不是很成熟.比如项目中使用protobuf,早就有人写了语法高亮(https://github.com/podgib/atom-protobuf),但是效果不是很好. ...
- jquery1.7.2的源码分析(五)$.support
$.support 的英文注释很详细的介绍的这里,就稍微的写了下 Query.support = (function() { var support, all, a, select, opt, inp ...