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

这篇将从项目实战开发,一步一步了解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. javaWeb防止恶意登陆或防盗链的使用

    使用场景:明明引用了一个正确的图片地址,但显示出来的却是一个红叉或写有“此图片仅限于***网站用户交流沟通使用”之类的“假图片”.用嗅探软件找到了多媒体资源的真实地址用下载软件仍然不能下载.下载一些资 ...

  2. 深入理解CSS选择器优先级的计算

    选择器的优先级关系到元素应用哪个样式.在CSS2.1的规范(http://www.w3.org/TR/2009/CR-CSS2-20090908/cascade.html#specificity)中是 ...

  3. SQL通过xml插入批量数据

    存储过程: CREATE PROCEDURE [dbo].[UP_PurchasexxxCard] @OrderInfo XMLASBEGIN SET NOCOUNT ON; DECLARE @Dat ...

  4. BZOJ3564 信号增幅仪

    http://www.lydsy.com/JudgeOnline/problem.php?id=3564 思路:先旋转坐标系,再缩进x坐标,把椭圆变成圆,然后做最小圆覆盖. 还有,为什么用srand( ...

  5. LeetCode_Decode Ways

    A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' - ...

  6. BZOJ 1018 [SHOI2008]堵塞的交通traffic

    1018: [SHOI2008]堵塞的交通traffic Time Limit: 3 Sec  Memory Limit: 162 MBSubmit: 2247  Solved: 706[Submit ...

  7. Android新浪微博客户端(一)——主框架搭建

    原文出自:方杰| http://fangjie.info/?p=62 转载请注明出处 提前声明的是,我是按照Ivan的这套教程学下来的. 首先,对于任何应用我们都需要建立一套消息处理机制,就是当用户在 ...

  8. C++ deepin

    访问类成员函数(cin.getline())方式是从访问结构成员变量方式衍生而来; C++结构体变量申明 struct关键字可省略; c++结构体变量声明初始化, = 可省略;但此需用在c++,大家都 ...

  9. PHP发送POST请求的三种方式

    class Request{ public static function post($url, $post_data = '', $timeout = 5){//curl $ch = curl_in ...

  10. Android 监听wifi广播的两种方式

    1.XML中声明 <receiver android:name=".NetworkConnectChangedReceiver" >             <i ...