DB 类使用, 控制器使用及模型使用
链接数据库:
- /config/database.php
- /.env
- DB_CONNECTION=mysql
- DB_HOST=127.0.0.1
- DB_PORT=3306
- DB_DATABASE=test
- DB_USERNAME=root
- DB_PASSWORD=root
控制器中查询 Mysql 数据
- use Illuminate\Support\Facades\DB;
- // 获取数据
- $data = DB::table('test')->where( array('id' => 1) )->get(); //tp 中 select();
- dump($data);
- $data = DB::table('test')->where( array('id' => 1) )->first(); //tp 中 find()
- dump($data);
- $data = DB::table('test')->where( array('id' => 1) )->pluck('name'); //tp 中 column()
- dump($data);
- $data = DB::table('test')->where( array('id' => 1) )->select('id','name')->get(); //tp 中 field()
- dump($data);
- //// 插入
- $data = DB::table('test')->insert( ['name' => 'john@example.com', 'sex' => 0]); // 返回 bool //tp 中 add()
- dump($data);
- $id = DB::table('test')->insertGetId(['name' => 'john@example.com', 'sex' => 0]);// 返回 id
- dump($id);
- // 更新
- $data = DB::table('test')
- ->where('id', 1)
- ->update(['sex' => 0]); // 返回更新条数 //tp 中 save()
- dump($data);
- DB::table('test')->where(['id'=> 1])->increment('num', 5); // 自增 //tp 中 setInc()
- DB::table('test')->where(['id'=> 2])->decrement('num', 5); //tp 中 setDec()
- // 删除
- DB::table('test')->where( ['id'=> 1] )->delete();
- DB::table('test')->truncate(); // 截断表 , 清空表内容, 自增恢复到初始值 1
- // 数据库事务处理
- DB::transaction(function(){
- $id = DB::table('test')->insertGetId(['name' => 'john@example.com', 'sex' => 0]);// 返回 id
- DB::table('test')->where(['id'=> $id])->increment('num', 5); // 自增
- });
- DB::beginTransaction();
- DB::rollBack();
- DB::commit();
来源: http://www.bubuko.com/infodetail-2709240.html