本人也算新手,高手请多多批评指正~~
在上一节中,我们完成了对数据库创建,现在已经有了网页所需的数据库表了,接下来我觉得要开始设计:怎么往数据库放数据以及怎样填充初始数据了。
MVC的第一项叫做MODEL。如何实现model?
Laravel 自带的 Eloquent ORM 为数据库提供了一个优雅的、简单的 ActiveRecord 实现。每一个数据库的表有一个对应的 "Model" 用来与这张表交互。在开始之前,确认已在 app/config/database.php 文件中配置好数据库连接。
关于MODEL部分的手册地址参看。
定义一个Eloquent模型,它自动对应了该类名的小写复数形式的数据表,比如User的模型对应了users的数据表。显然,我们需要有三个名称分别为User, Picture, 和Comment的模型。
具体地,我们究竟在models中定义了什么?model有什么用?
1.模型的建立方便了数据库操作,代替了db::形式的数据表操作,用类似User::的操作,明确了所操作的表对象,操作语句简单明了。
2.模型绑定,为在路由中注入模型实例提供了便捷的途径。例如,你可以向路由中注入匹配用户ID的整个模型实例,而不是仅仅注入用户ID。这样我们从只包含ID的路由中衍生出对持有该ID的整个类的一些操作。
3.类封装了该模型的一些方法,在路由中简单引用模型和方法就能实现路由的操作,当然,不乏类内函数间的调用和更多模块化的使用。
等等还有其他各种好处。
下面列出三个模型的代码:
1#......User.php。
这里我们其实并不用指定$table,如果没有定义$table,就会默认使用小写复数形式,它就是该模型使用的表名。
有时你可能希望限制包含在模型数组或JSON中的属性,比如密码,为此,在模型中添加一个隐藏属性$hidden。
另外,我们用hasmany指定了用户和它所发的图片的一个“一对多”的关系,因此我们可以在控制器中方便地使用如User::find(1)->pictures; 快速地定位到该用户所发的所有图片,进一步,可以执行约束检索的语句,比如:User:find(1)->pictures->where('title', '=', 'foo')->first(); 关系定义为关系数据库的查询提供了便利。
User模型使用了UserInterface和RemindableInterface接口,包括实现了保存用户名、密码、邮箱记录等功能。
<?php use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableInterface; use Illuminate\Database\Eloquent\Relations\HasMany; class User extends Eloquent implements UserInterface, RemindableInterface { /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password'); /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->getKey(); } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } /** * Get the e-mail address where password reminders are sent. * * @return string */ public function getReminderEmail() { return $this->email; } /** * define relationship with Picture. * * @return HasMany */ public function picture() { return $this->hasmany('Picture'); } /** * implement functions. * unnecessary on or below laravel 4.1. */ /** * Get the token value for the "remember me" session. * * @return string */ public function getRememberToken() { return $this->remember_token; } /** * Set the token value for the "remember me" session. * * @void */ public function setRememberToken($value) { $this->remember_token = $value; } /** * Get the column name for the "remember me" token. * * @return string */ public function getRememberTokenName() { return 'remember_token'; } }
2#......Picture.php
Picture定义了和Comment的一对多关系以及和User的多对一关系。
$fillable定义了该模型的可集体赋值的字段。当创建一个新的模型,您可以传递属性的数组到模型的构造函数。这些属性将通过集体赋值分配给模型。这是很方便的,但把用户的输入盲目地传给模型可能是一个严重的安全问题。如果把用户输入盲目地传递给模型,用户可以自由地修改任何或者全部模型的属性。基于这个原因,默认情况下所有 Eloquent 模型将防止集体赋值。
为了实现Picture的删除功能,完成delete函数,其中先要删除它所对应的comments再删除它本身。
<?php class Picture extends Eloquent { protected $fillable = ['title', 'description', 'image']; public function comments() { return $this->hasMany('Comment'); } public function user() { return $this->belongsto('User'); } public function delete() { foreach ($this->comments as $comment) { $comment->delete(); } return parent::delete(); } }
定义了和Picture的多对一关系,可集体赋值字段。
<?php class Comment extends Eloquent { protected $fillable = ['commenter', 'email', 'comment']; public function picture() { return $this->belongsTo('Picture'); } }
数据表的填充和表创建一样,也是由laravel的artisan命令执行的,具体参见迁移 & 数据填充
下面我们来实现数据填充的php文件
#......DatabaseSeeder.php
unguard()的功能参见注释。
这个文件是所有数据填充文件的入口,用它调用了UserTableSeeder.php文件的关于users数据表填充的相关内容,当然,如果想填充其他数据表,只要在该目录下定义并实现一个php文件,然后在这里call一下就可以了,当填充完成后,调用->command->info()输出成功信息。
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { /** * Disable all mass assignable restrictions. */ Eloquent::unguard(); $this->call('UserTableSeeder'); $this->command->info('User table seeded!'); } }
#......UserTableSeeder.php
在这里,我们定义了一个由数据表属性和值构成的键值对数组$user,把它填充到数据表中,这样我们就在users数据表中新增了一个用户,账号和密码均为admin。如果发现定义有误或者像重新定义,只要去掉语句 “DB::table('user')->truncate();” 前的注释再运行就可以了。
<?php class UserTableSeeder extends Seeder { public function run() { // Uncomment the below to wipe the table clean before populating // DB::table('user')->truncate(); $user = array( 'username' => 'admin', 'password' => Hash::make('admin'), 'created_at' => DB::raw('NOW()'), 'updated_at' => DB::raw('NOW()'), ); // Uncomment the below to run the seeder DB::table('users')->insert($user); } }
php artisan db:seed这样就完成了 对数据表的初始填充。查看MySQL数据库,我们会发现users表中出现了我们添加的新用户。其中的密码被加密了(使用了Hash:make()算法)。