.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学习系 ...
随机推荐
- DDMS中File Explorer无法查看data/data文件解决办法
http://www.cnblogs.com/smyhvae/p/3881477.html 找了个连接 问题描述:最近在学习Android SQLite中的SQLiteOpenHelper,使用SQ ...
- 一个读取propeties配置文件的工具类,线程安全的
public class ConfigUtil { private static Map<String,Properties> map = new HashMap<String,Pr ...
- hdu 4856 Tunnels
http://acm.hdu.edu.cn/showproblem.php?pid=4856 这道题就是搜索BFS+状压dp,把所经过的隧道的状态用二进制表示,然后dp就行.bfs求出每两个隧道的最短 ...
- assets文件夹资源的访问
访问assets文件夹中的文件,分为以下几个步骤:1.在Activity里面调用getAssets(),获取AssetManager引用2.调用AssetManager.open(String fil ...
- 有意思的数学题:Trapping Rain Water
LeetCode传送门 https://leetcode.com/problems/trapping-rain-water/ 目标:找出积木能容纳的水的“面积”,如图中黑色部分是积木,蓝色为可容纳水的 ...
- Linux系统编程(31)—— socket编程之TCP详解
TCP有源端口号和目的端口号,通讯的双方由IP地址和端口号标识.32位序号.32位确认序号.窗口大小稍后详细解释.4位首部长度和IP协议头类似,表示TCP协议头的长度,以4字节为单位,因此TCP协议头 ...
- hdu-1598
思路: 首先如果想到了Kruskal算法,那么下一步我们可能马上会想:那我们就从头开始写这个算法吧.然后一写就很容易发现一个问题——如果按照正常的Kruskal算法来做,那么start到end的舒适度 ...
- HDOJ 1248
完全背包. 模版. 物品的价值等价于体积. #include <stdio.h> #include <string.h> using namespace std; int ma ...
- redis 网络流程图 <一>
本来一直想好好读下redis源码.可是每次读了一点就不读了. 主要是没坚持每天都读. 隔几天看.就忘记前面的流程.就越来越不想看了. 很是蛋疼.这个还是要坚持读完的.打算这段时间都源码的时候.都大 ...
- h5新特性
!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></ ...