上一篇已经介绍开发环境的搭建,如果有问题可以在文章后留言。

这篇将从项目实战开发,一步一步了解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的更多相关文章

  1. .net转php laraval框架学习系列(一) 环境搭建

    之前也没写过什么博客,可能文章结构比较混乱,想到那写到哪. 主要是把自己学习中的经验写下来. 为什么选择laravel框架,是因为laravel框架目前是Php最流行的框架,深入研究后发现和asp.n ...

  2. .net转php laraval框架学习系列(三)项目实战---Route&Controllers

    本章来学习laravel的路由 一个简单的路由列子 Route::get('/', function() { return 'Hello World'; }); 路由的写法和Node的风格很相似.上面 ...

  3. .net转php laraval框架学习系列(四) 项目实战---View

    laravel的参考文档中view的讲解有些简单. 在实际项目开发中view的灵活性其实是非常大. 首先来看看laravel中的布局页 和asp.net mvc中有什么不同 <!DOCTYPE ...

  4. scrapy爬虫学习系列二:scrapy简单爬虫样例学习

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  5. 图机器学习(GML)&图神经网络(GNN)原理和代码实现(前置学习系列二)

    项目链接:https://aistudio.baidu.com/aistudio/projectdetail/4990947?contributionType=1 欢迎fork欢迎三连!文章篇幅有限, ...

  6. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

  7. Maven学习系列二(1-5)

    Maven学习系列二(1-5) 本文转自 QuantSeven 博客,讲解精炼易懂,适合入门,链接及截图如下 http://www.cnblogs.com/quanyongan/category/47 ...

  8. DocX开源WORD操作组件的学习系列二

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  9. [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参

    [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参 本文转自:http://www.cnblogs.com/babycool/p/3922738.html ASP.NET MVC学习系 ...

随机推荐

  1. 09 - 删除vtkDataObject中的ShouldIReleaseData() and ReleaseDataFlag 方法 VTK 6.0 迁移

    VTK6 引入了许多不兼容的变.其中之一是删除vtkDataObject中所有有关管道的方法.下面列出来的就是其中的一些方法: ShouldIReleaseData() SetReleaseDataF ...

  2. 转:Durandal快速入门

    Durandal是一个轻量级的JavaScript框架,其目标是单页面应用(SPAs)的开发变得简单而优雅.它支持MVC.MVP和MVVM等模式,因此不论你采用哪种类型的前端架构,Durandal都能 ...

  3. 转:浅析基于微软SQL Server 2012 Parallel Data Warehouse的大数据解决方案

    综述 随着越来越多的组织的数据从GB.TB级迈向PB级,标志着整个社会的信息化水平正在迈入新的时代 – 大数据时代.对海量数据的处理.分析能力,日益成为组织在这个时代决胜未来的关键因素,而基于大数据的 ...

  4. pm2 安装使用

    pm2 是全新开发的进程守护服务, 同时集成了负载均衡功能. 以及开机启动, 自动重启有问题进程. 还可以查看各服务进程状态. 使用方法参照:https://github.com/Unitech/pm ...

  5. Basic Printing Architecture

    https://blogs.technet.microsoft.com/askperf/2007/06/19/basic-printing-architecture/ Printer sharing, ...

  6. Android 解决listview中checkBox错位选择

    假如ListView,分成2页(或者设置数据可以纵向拉,可隐藏),每页3条数据,每个Listview的Item 里面有个checkBox,现在,当我选择第一页的前两天数据,翻到第二页,竟然第二页后两条 ...

  7. oracle11g rac asm 实例内存修改

    ASM实例内存修改 memory_max_target(它为静态参数,修改完成后需要重启实例) memory_target(它为动态参数,不需要重启实例) SQL> select name,is ...

  8. mysql System Tablespace

    System Tablespace 数据文件配置: mysql> show variables like '%innodb_data_file_path%'; +---------------- ...

  9. 设计模式(十):Decorator装饰者模式 -- 结构型模式

    1. 概述 若你从事过面向对象开发,实现给一个类或对象增加行为,使用继承机制,这是所有面向对象语言的一个基本特性.如果已经存在的一个类缺少某些方法,或者须要给方法添加更多的功能(魅力),你也许会仅仅继 ...

  10. cf500C New Year Book Reading

    C. New Year Book Reading time limit per test 2 seconds memory limit per test 256 megabytes input sta ...