2.laravel基础(二)数据库操作

DB facade(原始查找)

  • 新建数据表与连接数据库

    • 新建数据表
      CREAT TABLE IF NOT EXISTS student(
        'id' INT AUTO_INCREMENT PRIMARY KEY,
        'name' VARCHAR(255) NOT NULL DEFAULT '' COMMENT '姓名',
        'age' TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '年龄',
        'sex' TINYINT UNSIGNED NOT NULL DEFAULT 10 COMMENT '性别',
        'created_at' INIT NOT NULL DEFAULT 0 COMMENT '新增时间',
        'updated_at' INT NOT NULL DEFAULT 0 COMMENT '修改时间'
      )ENGINE=InnoDB DEFAULT CHARSET=UTF8 AUTO_INCREMENT=1001 COMMENT='学生表';
    • 连接数据库
      • config/database.php
      • .env(更改配置)
  • 使用DB facade 实现CURD

    建立StudentController控制器

     namespace App\Http\Controllers;
     use Illuminate\Support\Facades\DB;
     class StudentController extends Controller
    {
        public function test1()
        {
            //查询
           $studentArr = DB::select('select * from student');
            //新增
           $studentBool = DB::insert('insert into student(name,age) values(?,?)',[ 'sean',18]);
            //修改
           $studentNum = DB::update('update student set age = ? where name = ?',[20, 'sean']);
            //删除
           $studentNum = DB::delete('delete from student where id > ?', [1001]);
        }
    }

查询构造器

  • 查询构造器简介及新增数据
     //新增
     $studentBool = DB::table('student')->insert(['name'=>'imooc', 'age'=>18]);
     $studentId = DB::table('table')->insertGetId(['name'=>'sean', 'age'=>18]);
     DB::table('student')->insert([
       ['name'=>'name1', 'age'=>18],
       ['name'=>'name2', 'age'=>19]
     ]);
     //
  • 使用查询构造器修改数据

    • 更新为指定的内容
      $studentNum = DB::table('student')
         ->where('id', 12)
         ->update(['age'=>30]);
    • 自增和自减

      $studentNum = DB::table('student')->increment('age');//默认自增1
      $studentNum = DB::table('student')->increment('age' , 3);//自增3
      $studentNum = DB::table('student')->decrement('age');//默认自减1
      $studentNum = DB::table('student')->increment('age', 3);//默认自减3
      $studentNum = DB::table('student')
       ->where('id', 12)
       ->increment('age', 3);//默认自减3
      
      $studentNum = DB::table('student')
       ->where('id', 12)
       ->increment('age', 3, ['name, 'imooc']);//默认自减3,并将名字改成imooc
  • 使用查询构造器删除数据

    • delete

       DB::table('student')
           ->where('id', 15)
           ->delete();
      
       DB::table('student')
           ->where('id', '>=',13)
           ->delete();
    • truncate
       DB::table('student')->truncate();
  • 使用查询构造器查询数据

    • get()
       DB::table('student')->get();
    • first()
       DB::table('student')
           ->orderBy('id', 'desc')
           ->first();
    • where()

       DB::table('student')
          ->where('id', '>=', 1002)
          ->get();
      
       DB::table('student')
          ->whereRaw('id >= ? and age > ?', [1001, 18])
          ->get();
    • pluck() -- 返回结果集中指定的字段
       DB::table('student')
          ->pluck('name');
    • lists() -- 返回结果集中指定的字段,可以指定以什么作为下标
       DB::table('student')
          ->list('name', 'id');
    • select()
       DB::table('student')
          ->select('name', 'id')
         ->get();
    • chunk()
       DB::table('student')
          ->chunk(2, function($students){
             var_dump($students);
         //停止查询
          if(){
              return false;
          }
       });
  • 使用查询构造器中的聚合函数
    • count()
       DB::table('student')->count();
    • max()
       DB::table('student')->max('age');
    • min()
       DB::table('student')->min('age');
    • avg() -- 返回平均值
       DB::table('student')->avg('age');
    • sum() --某一列的和
       DB::table('student')->sum('age');

Eloquent ORM

  • Eloquent ORM 简介,模型建立及查询数据

    • 模型建立
        namespace App;
        use Illuminate\Database\Eloquent\Model;
        class Student extends Model{
          //指定表名
          protected $table = 'student';
          //指定主键
          protected $primaryKey = 'id';
        }
    • Eloquent ORM 中的查询

      • all()
          Student::all();
      • find()
          Student::find(1001);
      • findOrFail()
          Student::findOrFail(1001);
      • 查询构造器在ORM 中的使用

          Student::get();
          Student::where('id', '>' ,'1001')
            ->orderBy('age', 'desc')
            ->first();
          Student::chunk(2, function($students){
              var_dump($students);
          });
        
          Student::count();
          Student:;where('id' , '>=' , '1001')->max('age');
  • Eloquent ORM中新增数据,自定义时间戳及批量赋值的使用

    • 通过模型新增数据(涉及到自定义时间戳)

        $student = new Student();
        $student->name = 'sean';
        $student->age = 18;
        $student->save();

      时间戳设置
      在Student.php文件中增加如下方法

        //自动维护时间戳
        public $timestamps = true;
        //格式化时间为Unix时间戳
        protected function getDateFormat()
        {
            return time();
        }
        //把当前日期转为Unix时间原样输出,控制器中转为*2016-01-01 08:01:01*格式的方法为*date('Y-m-d H:i:s', $student->create_at)*
        protected function asDateTime($val)
        {
            return $val;
        }
    • 使用模型的Create方法新增数据(涉及到批量赋值)

        Student::create(
          ['name' => 'imooc', 'age'=>18]
        );
        //这样赋值会报错,因为没有设置允许批量赋值的字段
        //需要在Student.php模型文件中添加如下设置
        protected $fillable = ['name', 'age']; //指定可以批量赋值的字段
        protected $guarded = []; //指定不允许批量赋值的字段
      • firstOrCreate() -- 以属性查找用户,如果没有则新增一条实例
          Student::firstOrCreate(
            ['name'=>'immoc']
          );
      • firstOrNew() -- 以属性查找用户,如果没有则建立新的实例
          $student = Student::firstOrNew(
            ['name'=>'immoc']
          ); 
          $student->save(); //如果没有则新增一条
  • 使用Eloquent ORM修改数据
    • 通过模型更新
        $student = Student::find(1021);
        $student->name = 'Kitty';
        $bool = $student->save(); //会自动维护时间戳
    • 结合查询语句批量更新
        Student::where('id', '>' , 1019)
        -update(['age' => 41]);
  • 使用Eloquent ORM删除数据
    • 通过模型删除
        $student = Student::find(1021);
        $bool = $student->delete();
    • 通过主键值删除
        $num = Student::destroy(1020);
        $num = Student::destroy(1018, 1019);
        $num = Student::destroy([1016,1017]);
    • 根据指定条件删除
        Student::where('id', '>' , 1004)->delete();
posted @ 2017-03-13 23:21  涵叔  阅读(133)  评论(0)    收藏  举报