首页 > 其他分享 >laravel DB类,查询构造器

laravel DB类,查询构造器

时间:2022-10-09 17:11:44浏览次数:50  
标签:laravel name DB 查询 table where id users

laravel分为三大数据库操作(DB facade[原始查找],查询构造器[Query Builder],Eloquent ORM):

1,DB facade

use Illuminate\Support\Facades\DB;


DB::select('select * from users where id = :id', ['id' => 1]);
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::update('update users set votes = 100 where name = ?', ['John']);
DB::delete('delete from vipinfo where vip_ID= ?',[5]); 
DB::statement('drop table users');

  

2,查询构造器[Query Builder]

1. 查询所有
         $data = DB::table('user')->get();

 2. 查询所有,并指定字段 推荐使第一种方式
         $data = DB::table("user名")->select("name", "email")->get();
         $data = DB::table("user名") ->select(DB::raw('count(id) as count'), "email");
         $data = DB::table("user名")->selectRaw("count(id) as count, email")->get();
         $data = DB::table('user')->get(['name','age']);
         
 3. 查询单条数据
         $ret = DB::table('member')->where('id', 5)->first();
         
 4. 获取单个值
         $email = DB::table('users')->where('name', 'John')->value('email');

 5. 获取包含单列值的集合
         $titles = DB::table('roles')->pluck('title');
         // 会将 roles 表中的 name 字段当做键名,title 字段当做键值返回
         $roles = DB::table('roles')->pluck('title', 'name');

 6. 根据主键获取一条数据–find方法
         $user = DB::table('users')->find(1);
         $user = DB::table('users')->find([1, 2, 3]);
         
 7. 排序
         DB::table('users')->orderBy('name', 'desc') ->orderBy('rs.created_at', 'desc')->get();
         DB::table('orders')->orderByRaw('updated_at - created_at DESC')->get();
 
 9. 数据结果去重(distinct 方法会强制让查询返回的结果不重复)
         $users = DB::table('users')->distinct()->get();
 
 7. 查询前几条数据
         $data = DB::table('member')->where('active', 1)->take(10)->get();                
         $data = DB::table('member')->where('active', 1)->limit(10)->get();
         
 8. 分页查询
         $data = DB::table('member')->orderBy('id','desc')->paginate(10);
         $data = DB::table('member')->orderBy('id','desc')->offset(0)->limit(10)->get();
                 limit:表示限制输出的条数
                 offset:从什么地方开始,起始从0开始
         
 9. 条件查询
         DB::table("表名")->where([['a', '=', '1'],['b', '<>', '1']])->get();
         DB::table("表名")->where("name",">","10")->whereIn("titile",[1,2,3])->get();
         DB::table("表名")->where("name",">","10")->whereBetween("titile",[0,10])->get();
         DB::table("表名")->where("name",">","10")->orWhere("titile","=","0")->get();
         
 10. 分群(Group By)及 Having
         DB::table("users")->orderBy("name","desc")->groupBy("count")->having("count",">",100)->get()
         
 11. 模糊查询
          DB::table('users')->where('name', 'like', '%名称%')->get();
          
 12. 聚合查询 count, max, min, avg和 sum
          $users = DB::table('users')->count();
          $price = DB::table('orders')->max('price');

//count()统计记录条数
$nums=DB::table("vipinfo")->count();
echo $nums;
//max()某个字段的最大值,同理min是最小值
$max=DB::table("vipinfo")->max("vip_fenshu");
echo $max;
//avg()某个字段的平均值
$avg=DB::table("vipinfo")->avg("vip_fenshu");
echo $avg;
//sum()某个字段的和
$sum=DB::table("vipinfo")->sum("vip_fenshu")
 
 13. 强制让查询返回的结果不重复
         $users = DB::table('users')->distinct()->get();
 14. 关联查询
$result = DB::table('requirement_surveys as rs')
         ->select('rs.id', 'rs.process', 'r.requirement_id', 'r.title', 'u.name')
         ->leftJoin('requirements as r', 'rs.requirement_id', '=', 'r.requirement_id')
         ->leftJoin('users as u', 'u.id', '=', 'r.author_id')
         ->where('u.name', 'like', "%$name%")
         ->where('r.title', 'like', "%$title%")
         ->orderBy('rs.process', 'asc')
         ->orderBy('rs.created_at', 'desc')
         ->paginate($page_limit);
         
 $users = DB::table('users')
         ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
         ->get();
         
 $users = DB::table('users')
         ->join('contacts', 'users.id', '=', 'contacts.user_id')
         ->join('orders', 'users.id', '=', 'orders.user_id')
         ->select('users.*', 'contacts.phone', 'orders.price')
         ->get();
 15,复制查询
//查询出现次数最多的商品名
 $product_name = Db::table('guild_pay.order')
         ->where('status', '=', 1)
         ->select(DB::raw('count(*) as count, product_name'))
         ->orderBy('count', 'desc')
         ->groupBy('product_name')
         ->first();

 //两个数据库中有两个不相关的表,我需要将它们合并,并在order2中新增不存在的字段,并赋予默认值
 $product_name = '默认值';
 $news = DB::table("guild_pay.order1")
         ->where('status', '=', 1)
         ->selectRaw('product_name','order_no','money','create_time');
 $res = Db::table('guild_pay.order2')
           ->where('status', '=', 1)
         ->union($news)
         ->selectRaw('IFNULL(null, ?) as product_name, order_no, money, create_time', [$product_name])
         ->orderBy('create_time', 'desc')
         ->paginate(10)->toArray();
 ps:记得两个表的key要一一对应,不可以一边多一边少,也不可以换位置
 

删除

$ret = DB::table('member')->where('id',2)->delete();
$num=DB::table("vipinfo")->truncate();//删除整表,不能恢复,谨慎使用
增加
1. 添加单条数据
         $ret = DB::table('member')->insertGetId($data);
         $ret = DB::table('member')->insert($data);
         insert() 可以同时添加一条或多条,返回值是布尔类型。
         insertGetId() 只能添加一条数据,返回得到插入时的ID值。
     
 2. 添加多条记录
         $ret = DB::table('member')->insert([
             ['name'=>'AAAA','age'=>20,'email'=>'[email protected]'],
             ['name'=>'BBBB','age'=>30,'email'=>'[email protected]'],
         ]);
 
修改
$ret = DB::table('member')->where('id', 2)->update([
     'name' => '修改一下',
     'age'  => 50
 ]);
$bool=DB::table("vipinfo")->where('vip_ID',6)->update(['vip_fenshu'=>500]);
echo $bool;

//自增

$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu");//自增1

$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3);//自增3

echo $bool;

//自减

$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu");//自1

$bool=DB::table("vipinfo")->where('vip_ID',6)->decrement("vip_fenshu",3);//自增3

echo $bool;

//自增时再修改其他字段

$bool=DB::table("vipinfo")->where('vip_ID',6)->increment("vip_fenshu",3,['vip_name'=>'dbdibi']);//自增3
 

 

标签:laravel,name,DB,查询,table,where,id,users
From: https://www.cnblogs.com/fslnet/p/16772831.html

相关文章

  • MySQL慢查询优化
    日常开发中,我们经常会遇到数据库慢查询。那么导致数据慢查询都有哪些常见的原因?今天就跟大家聊聊导致数据库慢查询的12个常见原因,以及对应的解决方法。   1.SQL......
  • 【博学谷学习记录】超强总结,用心分享|MySql连接查询超详细总结
    一、概述在实际开发中,大部分情况下都不是在单表中进行数据操作,一般都是多张表进行联合查询。通常一个业务就会对应的有好几张表。MySql中的连接查询分为交叉连接,内连......
  • 如何从 InfluxDB/OpenTSDB 无缝连接到 TDengine
    小 T 导读:taosAdapter是 TDengine 这款时序数据库(TimeSeriesDatabase)的配套工具,是TDengine集群和应用程序之间的桥梁和适配器。当我们需要从数据收集代理软件(如T......
  • 云图说丨带你了解GaussDB(for Redis)双活解决方案
    摘要:GaussDB(forRedis)推出了双活解决方案,基于GaussDBNoSQL统一架构,通过两个数据库实例之间的数据同步,达成数据的一致性。本文分享自华为云社区《【云图说】一张图了解G......
  • mysql之select查询篇2
    一、多表查询1、多表查询概述1.1、为什么要多表查询执行多条单表查询语句延时数据放在一个表出现字段数据冗余1.2、笛卡尔积错误selectuseriddepnamefromuser,dep出现每......
  • 十八: 索引优化与查询优化
    索引优化与查询优化都有哪些维度可以进行数据库调优?简言之:索引失效、没有充分利用到索引---索引建立关联查询太多JOIN(设计缺陷或不得已的需求)---SQL优化......
  • mysql 中sql 语句查询今天、昨天、近7天、近30天、一个月内、上一月 数据
    几个小时内的数据DATE_SUB(NOW(),INTERVAL5HOUR)今天select * from 表名 where to_days(时间字段名) = to_days(now());昨天SELECT * FROM 表名 WHERE T......
  • MyISAM 和 InnoDB 索引实现
     MyISAM索引实现MyISAM引擎使用B+Tree作为索引结构,叶节点的data域存放的是数据记录的地址。下图是MyISAM索引的原理图: 这里设表一共有三列,假设我们以Col1为主键,则上图是......
  • MongoDB安装
    首先,我们去官网看看,MongoDB下载。  先把安装包下载下来,然后就是正常安装软件的步骤:双击打开,next=> 打上勾,继续next=>   选Custom  Browser选择安装路......
  • 如何在Excel/WPS表格中查询图书信息?
    给您一个ISBN编号,您能查出它的书名、作者、价格等信息吗?答案一定是可以。但如果几百上千条ISBN编号在表格中需要查询,如何能快速的获取信息呢?相信很多老师会有这种困惑。今......