创建表
php artisan make:migration create_good_table –create=goods
然后找到相应的迁移文件
如:/database/migrations/2016_07_04_083644_goods.php:
可以对表中的字段进行相关的操作
数据迁移操作
php artisan migrate 执行所有迁移文件
php artisan migrate:rollback 回退到执行迁移前的状态
php artisan migrate:reset 回退到所有迁移之前的初始状态
php artisan migrate:refresh 回退到初始状态,再次执行所有迁移文件
DB类操作数据库
使用前 先 use DB;
增 insert
插入单行 (注意看数组的键)
DB::table('users')->insert(['email'=>'lisi@qq.com']);
插入多行 (多维数组)
DB::table('users')->insert([
['email'=>'lisi@qq.com'],
['email'=>'wang@yy.com'],
]);
获取主键值:insertGetId()
改 update
典型修改
DB::table('users')->where('id', 1)->update(['age' => 19])
某个字段的增加或减少
DB::table('users')->where('id',1)->increment('age');
DB::table('users')->where('id',2)->increment('age', 3);
DB::table('users')->where('id',3)->decrement('age');
DB::table('users')->where('id',4)->decrement('age', 3);
删 delete
DB::table('users')->where('id' , '>' , '6')->delete();
查 select
// select * from users;
DB::table('users')->get();
// select * from user where id > 6
DB::table('users')->where('id' , > 6)->get();
// select id,email from users where id > 6
DB::table('users')->select('id','email')->where('id' , > 6)->get();
// select * from users where id=6 取出单行,返回
DB::table('users')->where('id',6)->first()
注意:取出的数据,无论是单行还是多行,每一行数据都是以一个对象的形式存在的
Model的使用
model 在\app\下
创建model
php artisan make:model Msg
php artisan migrate
使用前先引用
use App\Msg;
增
public function add() {
$msg = new Msg();
$msg->title = $_POST['title'];
$msg->content= $_POST['title'];
return $msg->save() ? 'OK' : 'fail';
}
改
public function up($id) {
$msg = Msg::find($id);
$msg->title = $_POST['title'];
$msg->content= $_POST['content'];
return $msg->save() ? 'OK' : 'fail';
}
删
public function del($id) {
$msg = Msg::find($id);
return $msg->delete() ? 'ok' : 'fail';
}
查
查单行:Msg::find($id) // 按id查
查多行 all() 和 get()
// 无条件查所有行. select 列1,列2 from msgs;
Msg::all(['列1','列2']);
// 按条件查多行
Msg::where('id','>',2)->get(['列1','列2']);
排序
// select ... where id > 2 order by id desc;
Msg::where('id','>',2)->orderBy('id','desc')->get()
限制条目
// select .. where id>2 order by id desc limit 2,1;
Msg::where('id','>',2)->orderBy('id','desc')->skip(2)->take(1)->get();
统计
Msg::count();
Msg::avg('id');
Msg::min('id');
Msg::max('id');
Msg::sum('id');
分组
// 用DB::raw()方法,raw是"裸,不修饰的"意思
Goods::groupBy('cat_id')->get(['cat_id',DB::raw('avg(price)')]) );
model的约定
表名的约定
默认表名为Model名+s,可能通过的model类的table属性来指定表名.
class XxModel extends Model {
protected $table = 'yourTableName';
}
Model默认认为,每张表都有一个叫做id的主键,你可以通过primaryKey属性来指定主键列名.
class XxModel extends Model {
protected $primaryKey = 'Xx_id';
}
Model默认有这2个字段,且在更新行时,会自动帮你更新这两个字段.
如果不想这样,甚至不想要这2个字段,可以把model的timestamps属性设为false
class XxModel extends Model {
public $timestamps = false;
}