zoukankan      html  css  js  c++  java
  • DB门面,查询构建器,Eloquent ORM三者的CURD

    一.DB门面
    1.insert
    DB::insert('insert into table(`name`) value(?)', ['test']);
    
    2.update
    DB::update('update into table set name=? where id=?', ['test', 10]);
    
    3.delete
    DB::delete('delete from tb where id=?', [1]);
    
    4.select
    DB:select('select * from tb');
    
    
    二.查询构建器(使用查询构建器不会触发模型事件)
    1.insert
    DB::table('tb')->insert(['name' => 'test']);
    
    2.update
    DB::table('tb')->where('id', 1)->update(['name' => 'test']);
    
    3.delete
    DB::table('tb')->where('id', 1)->delete();
    
    4.select
    # 多条
    DB::table('tb')->where('cat', 1)->orWhere(function($query){
    		return $query->where('vote', '>', 1);
    	})->orderBy('id', 'DESC')->select('name')->skip(5)->take(10)->get();
    
    #一条
    DB::table('tb')->where('cat', 1)->first();
    
    #一列
    DB::table('tb')->where('cat', 1)->value('col');
    DB::table('tb')->where('cat', 1)->pluck('col');
    
    
    三.Eloquent ORM(本身就是查询构建器)
    1.insert(也可以使用insert方法插入一个数组到数据库,但不会触发事件)
    
    $model = new TbModel;
    $model->name = 'test';
    $model->save();
    
    使用create,但需要模型限定fillable或guarded
    TbModel::create(['name' => 'test']);
    
    create和save的区别是
    a.create的参数接受的一个字段数组,save也可以接受一个数组,但是只是用来指定timestamps的值
    b.create返回的是一个model,save只返回true或false
    
    2.update
    $model = TbModel::first(1);
    $model->name = 'test';
    $model->save();
    
    带where并且只更新指定字段,和查询构建器一样
    $model = TbModel::first(1);
    $model->where('time', today())->update(['delayed'=>1]);
    
    save无法和where共用,它是根据主键来保存的;保存受影响的字段;
    
    3.delete
    TbModel::first(1)->delete();
    TbModel::destory(1);
    Flight::where('id', 1)->delete();
    
    4.select
    #多条
    TbModel::all();//不能带where
    TbModel::where('cat', 1)->get(); //可以带where
    
    #单条
    TbModel::find(1); // 利用主键取回
    如果查询条件带where,而且不是主键,则使用first
    TbModel::where('time', today())->first();
      
    

      

  • 相关阅读:
    隔行变色&&鼠标移入变色
    滚动之固定顶部
    页面滚动之回到顶部
    定时器之秒表
    定时器之小僵尸的移动
    tomcat+spring+https
    域名相关
    【软件创意】智能Goals (android)
    【神一样的作业】二维数组连续的二维子数组的和(元素可以连续)
    【软件工程】敏捷开发方法的总结
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7018653.html
Copyright © 2011-2022 走看看