.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学习系 ...
随机推荐
- Centos7 wget和普通下载有区别
今天下的禅道 wget和用win下载之后再ssh传过去,效果不一样 wget不能正常启动禅道.回来要探讨一下wget的不同之处,先记下来
- 转:redis windows下的环境搭建
原文来自于:http://www.2cto.com/os/201204/125971.html 下载地址:https://github.com/dmajkic/redis/downloads 下载 ...
- ural 1207 Median on the Plane
极角排序 #include <cstdio> #include <cstring> #include <algorithm> #include <cmath& ...
- MYSQL正式环境主从复制(不锁表,不停服务)
参考URL: http://rfyiamcool.blog.51cto.com/1030776/1016636/ 原因源于其实以前环境是有MYSQL主从复制的,且最开始主从复制之间是OK的. 但由于日 ...
- POJ_1321——棋盘问题,回溯+剪枝
Description 在一个给定形状的棋盘(形状可能是不规则的)上面摆放棋子,棋子没有区别.要求摆放时任意的两个棋子不能放在棋盘中的同一行或者同一列,请编程求解对于给定形状和大小的棋盘,摆放k个棋子 ...
- bfs 记录和打印最短路径
Poj3984 迷宫问题 #include <iostream> #include <algorithm> #include <cstdio> #include & ...
- Button 对象
<html> <form> <input type="button" value="提交" accesskey="b&q ...
- FTP服务器上删除文件夹失败
很多人都知道:要删除FTP服务器上的文件夹时,必须确保文件夹下面没有其他文件,否则会删除失败! 可是,有些服务器考虑到安全等因素,通常会隐藏以点开始的文件名,例如“.test.txt”.于是,有的坏人 ...
- Vbox中Ubuntu的安装和共享文件夹设置
1. 选择版本 1.1 Ubuntu桌面版与服务器版的区别 桌面版与服务器版,只要发布版本号一致,这两者从核心来说也就是相同的,唯一的差别在于它们的预期用途.桌面版面向个人电脑使用者,可以进行文字处理 ...
- Linux进程实时监控 - htop
htop 是一个 Linux 下的交互式的进程浏览器,top的增强版 htop: 进入:htop 退出:按q键 常用操作: ...