Laravel学习记录--DB类操作数据库

DB类操作数据库

简单增删改查

use DB

一,添加
1.insert类 单条添加

   $data = ['title'=>'laravel','content'=>'sql-insert'];
    DB::table('msgs')->insert($data);

2.多条添加

$data = array(
    array(
        'title'=>'1',
        'content'=>'2'
    ),
    array(
        'title'=>'2',
        'content'=>'3'
    )
)
DB::table('msgs')->insert('$data');

3.插入一条数据并返回insert操作产生的ID

 DB::table('msgs')->insertGetId($data);//只能使用添加一条数据

二,修改

1.简单修改

$data = ['title'=>'修改标题'];
DB::table('msgs')->where('id',1)->update($data);//执行成功返回1

2.在原字段的基础上,增长或减少 ,类似于浏览次数或点赞

   DB::table('user')->where('id',1)->increment('age');//默认步长一
   DB:table('user')->where('id',2)->increment('age',3);//修改步长为三

    DB............................->decrement('age');//默认减一
    ................................->decrement('age',4)//修改减4
    //    成功返回1

三,删除

  DB::table('goods')->where('id','>',4)->delete();

2.清空表

 DB::table('user')->truncate( );

四,查询

  //查询值返回类似对象,而不是关联数组
    //普通查询:
    DB::table('goods')->get();//== select * from goods
    //返回对象包含多维数组
      
    //条件查询:
    DB::table('goods')->where('id','>',6)->get();//==  select * from goods where id > 6;
      
  // 查询多字段:
    DB::table('goods')->select('id','email')->where('id','>',6)->get();//== select id,emaill from goods where id > 6
       
   // 查询单行数据:
    DB::table('goods')->where('id','>',6)->first();//== select * from goods where id > 6;//取出单行数据
    //返回对象
    
    //查询某个字段:
    DB::table('goods')->where('id',3)->value('title');//返回字符串
   
    //查询某表单个字段:
    DB::table('goods')->pluck('content');//返回对象多维数组
   // 使用原生sql 
    DB::select('select * from gods');
    //返回对象多维数组
发布了17 篇原创文章 · 获赞 0 · 访问量 462

猜你喜欢

转载自blog.csdn.net/weixin_45143481/article/details/103937066