
1 // auto increment id (primary key)
2 $table->increments('id')
3
4 $table->string('name')
5 $table->integer('age')->nullable()
6 $table->boolean('active')->default(1)
7 $table->integer('role_id')->unsigned()
8 $table->text('bio')
9
10 // created_at, updated_at DATETIME
11 $table->timestamps()
实际上生成的SQL代码为:
1 `id` INT(11) NOT NULL AUTO_INCREMENT,
2 `name` VARCHAR(255) NOT NULL,
3 `age` INT(11) NULL DEFAULT NULL,
4 `active` TINYINT(4) NOT NULL DEFAULT '1',
5 `role_id` INT(10) UNSIGNED NOT NULL,
6 `bio` TEXT NOT NULL,
7
8 `created_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
9 `updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
我们会意识到,迁移是多么的强大,我们自需要记住一些结构生成器方法而不是写晦涩难懂的SQL DDL代码。
我们创建了表,那我们想要回滚的时候怎么办呢?只需要在于up()方法对应的down()方法中使用drop()方法即可。
1 public function down()
2 {
3 Schema::drop('authors')
4 }
这个方法非常简单,只有一行。它的全部作用就是删除”authors”表,如果你熟悉sql,它等同于DROP TABLE authors。
现在,我们已经写好了架构,我们就可以对数据库执行迁移文件了。转到命令行工具,跳转到应用目录下,运行artisan migrate命令:
1 php artisan migrate
执行结果如下:
检查数据库,你会发现已经有了”authors”表,
表结构如下:
如果你要使用sql语句实现这张表,那么sql查询语句如下:
1 CREATE TABLE `authors` (
2 id int AUTO_INCREMENT NOT NULL,
3 namevarchar(255) NOT NULL,
4 age int,
5 active tinyint NOT NULL DEFAULT '1',
6 role_id int(10) UNSIGNED NOT NULL,
7 bio text NOT NULL,
8 created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
9 updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
10 email varchar(64) NOT NULL,
11 /* Keys */
12 PRIMARY KEY (id)
13 ) ENGINE = InnoDB
现在假设我们上次的执行存在错误想要回滚,我们自需要使用artisan命令行工具执行下面的命令即可:下一次,如果你想修改数据模型,你可以创建一个新的迁移,再次执行命令artisan migrate。每一次执行artisan migrate命令,它都会根据时间戳去检查哪些没有执行,如果执行了,就跳到下一个文件,如果没有执行,就执行这次迁移,直到执行完所有迁移文件。
1 php artisan migrate:rollback
运行如下:
你会发现,表”authors”已经从数据库中删除了。
现在重新创建”authors”表,执行artisan migrate命令:
1 php artisan migrate
这时,表”authors”又重新创建了。
但是我想在表中添加”email”列。先使用artisan创建新的迁移文件:
php artisan migrate:make add_email_to_authors_table
运行结果如下:
然后编辑2014_03_12_051119_add_email_to_authors_table.php文件,添加电子邮件列。我们使用Schema::table()方法,有两个参数:表名、闭包函数(在此函数内添加字段)。
1 public function up()
2 {
3 Schema::table('authors', function($table) {
4 $table ->string('email', 64)
5 })
6 }
有了添加方法,当然也需要添加回滚方法了,这里再次使用Schema::table()方法。
1 public function down()
2 {
3 Schema::table('authors', function($table) {
4 $table ->dropColumn('email')
5 })
6 }
上面的方法使用了dropColumn()方法上出列。
现在运行artisan命令运行该迁移文件如下:
刷新数据库表,你会发现”email”字段已经在”authors”中出现了,如下图:
如果我们回滚了这次迁移,那么email字段会从表中删除。
Artisan命令还有一个更强大的命令行,它可以回滚所有的迁移:
一、Selects
检索表中的所有行
代码如下:
$users = DB::table('users')->get()
foreach ($users as $user)
{
var_dump($user->name)
}
从表检索单个行
代码如下:
$user = DB::table('users')->where('name', 'John')->first()
var_dump($user->name)
检索单个列的行
代码如下:
$name = DB::table('users')->where('name', 'John')->pluck('name')
检索一个列值列表
代码如下:$roles = DB::table('roles')->lists('title')
该方法将返回一个数组标题的作用。你也可以指定一个自定义的键列返回的数组
代码如下:
$roles = DB::table('roles')->lists('title', 'name')
指定一个Select子句
代码如下:
$users = DB::table('users')->select('name', 'email')->get()
$users = DB::table('users')->distinct()->get()
$users = DB::table('users')->select('name as user_name')->get()
Select子句添加到一个现有的查询$query = DB::table('users')->select('name')
代码如下:
$users = $query->addSelect('age')->get()where
代码如下:
$users = DB::table('users')->where('votes', '>', 100)->get()
OR
代码如下:
$users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John')->get()
Where Between
代码如下:$users = DB::table('users')->whereBetween('votes', array(1, 100))->get()
Where Not Between
代码如下:
$users = DB::table('users')->whereNotBetween('votes', array(1, 100))->get()
Where In With An Array
代码如下:
$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get()
$users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get()
Using Where Null To Find Records With Unset Values
代码如下:
$users = DB::table('users')->whereNull('updated_at')->get()
Order By, Group By, And Having
代码如下:
$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100)->get()
Offset &Limit
代码如下:
$users = DB::table('users')->skip(10)->take(5)->get()
二、连接
Joins
查询构建器也可以用来编写连接语句。看看下面的例子:
Basic Join Statement
代码如下:
DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get()
左连接语句
代码如下:
DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get()
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id', '=', 'contacts.user_id')->orOn(...)
})
->get()
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5)
})
->get()
三、分组
有时候,您可能需要创建更高级的where子句,如“存在”或嵌套参数分组。Laravel query builder可以处理这些:
复制代码 代码如下:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin')
})
->get()
上面的查询将产生以下SQL:
代码如下:
select * from users where name = 'John' or (votes >100 and title
<>'Admin')
Exists Statements
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id')
})
->get()
代码如下:
select * from userswhere exists (
select 1 from orders where orders.user_id = users.id
)
四、聚合
查询构建器还提供了各种聚合方法,如统计,马克斯,min,avg和总和。
Using Aggregate Methods
代码如下:
$users = DB::table('users')->count()
$price = DB::table('orders')->max('price')
$price = DB::table('orders')->min('price')
$price = DB::table('orders')->avg('price')
$total = DB::table('users')->sum('votes')
Raw Expressions
有时您可能需要使用一个原始表达式的查询。这些表达式将注入的查询字符串,所以小心不要创建任何SQL注入点!创建一个原始表达式,可以使用DB:rawmethod:
Using A Raw Expression
代码如下:
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get()
递增或递减一个列的值
代码如下:
DB::table('users')->increment('votes')
DB::table('users')->increment('votes', 5)
DB::table('users')->decrement('votes')
DB::table('users')->decrement('votes', 5)
您还可以指定额外的列更新:
代码如下:
DB::table('users')->increment('votes', 1, array('name' =>'John'))
Inserts
将记录插入表
复制代码 代码如下:
DB::table('users')->insert(array('email' =>'john@example.com', 'votes' =>0)
)
将记录插入表自动增加的ID
如果表,有一个自动递增的id字段使用insertGetId插入一个记录和检索id:
代码如下:
$id = DB::table('users')->insertGetId(
array('email' =>'john@example.com', 'votes' =>0)
)
注意:当使用PostgreSQL insertGetId方法预计,自增列被命名为“id”。
多个记录插入到表中
代码如下:
DB::table('users')->insert(array(
array('email' =>'taylor@example.com', 'votes' =>0),
array('email' =>'dayle@example.com', 'votes' =>0),
))
四、Updates
更新一个表中的记录
代码如下:
DB::table('users')
->where('id', 1)
->update(array('votes' =>1))
五、 Deletes
删除表中的记录
代码如下:
DB::table('users')->where('votes', '<', 100)->delete()
删除表中的所有记录
代码如下:
DB::table('users')->delete()
删除一个表
代码如下:
DB::table('users')->truncate()
六、Unions
查询构建器还提供了一种快速的方法来“联盟”两个查询:
代码如下:
$first = DB::table('users')->whereNull('first_name')
$users = DB::table('users')->whereNull('last_name')->union($first)->get()
unionAll方法也可以,有相同的方法签名。
Pessimistic Locking
查询构建器包括一些“悲观锁定”功能来帮助你做你的SELECT语句。运行SELECT语句“共享锁”,你可以使用sharedLock方法查询:
代码如下:
DB::table('users')->where('votes', '>',
100)->sharedLock()->get()
更新“锁”在一个SELECT语句,您可以使用lockForUpdate方法查询:
代码如下:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get()
七、缓存查询
你可以轻松地缓存查询的结果使用记忆法:
代码如下:
$users = DB::table('users')->remember(10)->get()
在本例中,查询的结果将为十分钟被缓存。查询结果缓存时,不会对数据库运行,结果将从默认的缓存加载驱动程序指定您的应用程序。
如果您使用的是支持缓存的司机,还可以添加标签来缓存:
代码如下:
$users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get()。
Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。
在Laravel中已经具有了一套高级的PHP ActiveRecord实现 -- Eloquent ORM。它能方便的将"约束(constraints)"应用到关系的双方,这样你就具有了对数据的完全控制,而且享受到ActiveRecord的所有便利。Eloquent原生支持Fluent中查询构造器(query-builder)的所有方法。
->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'))foreach($posts as $p){
$data[] = array(
'id' =>$p ->id,
'support' =>$p ->support,
'against' =>$p ->against,
'username'=>$p ->username,
'post_author' =>$p ->post_author,
'post_title' =>$p ->post_title,
'post_body' =>$p ->post_body
)
}
$res = View::make('home.index')
->with('posts', $data)
Cache::forever('staticPageCache_home', $res)
}
// 返回缓存的数据
return Cache::get('staticPageCache_home')
}
}
这里我用到了三个api
1). Cache::has ,这个判断是说如果当前不存在 staticPageCache_home 这个名字的缓存, 就立即去取数据
2). Cache::forever, 这个从用例文档里面可知是"永久缓存"的意思, 因为我一般都是很勤劳的,如果发表了博文,自己再去后台立即刷新一下缓存就好了, 所以不需要设置过期啊失效时间之类的, 当然这个是要按各自的具体需求来的
3). Cache::get , 这句是从缓存里面取出 staticPageCache_home 这个名字的缓存, 然后作为响应内容返回
嗯, 就这么简单, 呵呵, 一个基本的缓存功能就完成了, laravel的确是不错地!
3. 为后台添加刷新缓存功能
还是贴代码吧, 不过也很简单:
// 刷新首页缓存(暂时只支持首页)
public function get_refreshcache() {
/*
@var $GID admin组id
*/
$GID = 1
if ( Auth::user() ->gid === 1 ) {
$data = array()
$posts = Post::with('user')
->join('users', 'users.id', '=', 'posts.post_author')
->order_by('posts.created_at', 'desc')
->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'))
foreach($posts as $p){
$data[] = array(
'id' =>$p ->id,
'support' =>$p ->support,
'against' =>$p ->against,
'username'=>$p ->username,
'post_author' =>$p ->post_author,
'post_title' =>$p ->post_title,
'post_body' =>$p ->post_body
)
}
$res = View::make('home.index')
->with('posts', $data)
Cache::forever('staticPageCache_home', $res)
return '刷新首页缓存成功!'
}
return '对不起,只有管理员组才可进行此 *** 作!'
}
我给后台添加了一个项目, 对应这个方法, 方法内容和首页的大同小异, 取数据, 然后Cache::forever 刷新一下缓存,就这么简单,当然了,上面的Auth::user() 判断是个简单的判断,只有管理员组才能进行刷新 *** 作,呵呵
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)