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();
      
    

      

  • 相关阅读:
    敏捷开发系列学习总结(5)——这几招搞定团队协同Coding
    敏捷开发系列学习总结(4)—Git管理工具sourcetree的安装
    Java基础学习总结(74)——Java常见笔试题及答案汇总
    iOS 极光推送
    iOS UI控件没有显示时的调试技巧
    iOS 搜索之拼音搜索
    iOS MJExtension框架之字典数组转模型数组
    iOS 单例
    iOS 切换键盘
    iOS 正则表达式
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7018653.html
Copyright © 2011-2022 走看看