1. 数据库操作
  2. 执行原生SQL
  3. //查询
  4. $emp = DB::select('select * from employees where emp_no = 1');
  5. $emp = DB::select('select * from employees where emp_no = ? and gender = ?',[1,'M']);
  6. $emp = DB::select('select * from employees where emp_no = :empNo and gender = :gender',['empNo'=>1,'gender'=>'M']);
  7.  
  8. //插入
  9. DB::insert('insert into employees(first_name,last_name) values(?,?,?)',['Jack','Ma']);
  10. //更新,返回受影响的行数
  11. $affected = DB::update('update employees set gender = ? where emp_no = ?',['M',123]);
  12. //删除,返回被删除的行数
  13. $deleted = DB::delete('delete from employees where first_name = ?',['Jack']);
  14. //运行通用语句,不返回任何值
  15. DB::statement('drop table employees');
  16.  
  17. 事务
  18. //如果事务闭包中抛出异常,事务将会自动回滚;如果闭包执行成功,事务将会自动提交:
  19. DB::transaction(function(){
  20. DB::insert('insert into employees(first_name,last_name) values(?,?,?)',['Jack','Ma']);
  21. $affected = DB::update('update employees set gender = ? where emp_no = ?',['M',123]);
  22. });
  23.  
  24. //手动开启事务
  25. DB::beginTransaction();
  26. //手动回滚
  27. DB::rollBack();
  28. //手动提交
  29. DB::commit();
  30.  
  31. 查询构建器
  32. table()
  33. 通过DB门面的table()函数来获取一个查询构建器实例。
  34.  
  35. get()
  36. $emps = DB::table('employees').get();
  37. 1
  38. 返回包含结果集额的Illuminate\Support\Collection,其中每一个结果都是 PHP StdClass 对象实例
  39.  
  40. first()
  41. $emp = DB::table('employees')->first();
  42. 1
  43. 从数据表中获取一行数据
  44.  
  45. value()
  46. $values = DB::table('employees')->where('emp_no','>=',499995)->value('first_name');
  47. 1
  48. 只获取第一条结果的某一列的数据
  49.  
  50. pluck()
  51. value类似,但是返回所有符合条件的记录列数组。
  52.  
  53. chunk()
  54. DB::table('employees')->where('emp_no','>=',499980)->orderby('emp_no')->chunk(10,function($emps){
  55. foreach ($emps as $emp) {
  56. echo $emp->first_name. '<br>';
  57. }
  58. });
  59. 1
  60. 2
  61. 3
  62. 4
  63. 5
  64. 将查询结果分块在回调函数中进行处理。
  65.  
  66. 聚合函数
  67. //count()
  68. $result = DB::table('employees')->where('emp_no','>=',499980)->count();
  69. //max()
  70. $result = DB::table('salaries')->max('salary');
  71. //min()
  72. $result = DB::table('salaries')->min('salary');
  73. //sum()
  74. $result = DB::table('salaries')->where('emp_no','>=',499980)->sum('salary');
  75. //avg()
  76. $result = DB::table('salaries')->where('emp_no','>=',499980)->avg('salary');
  77.  
  78. exists()、doesntExist
  79. $result = DB::table('employees')->where('emp_no','=','500000')->exists();
  80. $result = DB::table('employees')->where('emp_no','=','500000')->doesntExist();
  81.  
  82. 判断结果是否存在或不存在
  83.  
  84. select(),andSelect()
  85. $result = DB::table('employees')->where('emp_no','>=','499980')->select('first_name','last_name')->get();
  86. //上面的查询等同于:
  87. $query = DB::table('employees')->where('emp_no','>=','499980')->select('first_name');
  88. $result = $query->andSelect('last_name')->get();
  89.  
  90. 指定查询的列
  91.  
  92. distinct()
  93. $result = DB::table('employees')->where('emp_no','>=','499980')->select('first_name','last_name')->distinct()->get();
  94. 1
  95. 过滤重复结果
  96.  
  97. 原生语句
  98. DB::Raw()
  99.  
  100. $result = DB::table('employees')->select(DB::raw('count(1) as num'))->where('emp_no','>=', 499980')->get();
  101. 1
  102. whereRaw()
  103.  
  104. $result = DB::table('employees')->select(DB::raw('count(1) as num'))->whereRaw('emp_no>=?',[499980])->get();
  105. 1
  106. 此外还有orWhereRaw(),havingRaw(),orhavingRaw(),orderByRaw()
  107.  
  108. Join
  109. join
  110.  
  111. $result = DB::table('employees')->join('salaries','employees.emp_no','=','salaries.emp_no')->where('employees.emp_no','>=','499980')->get();
  112. 1
  113. leftJoin,rightJoin类似。
  114.  
  115. crossJoin():生成一个笛卡尔积
  116.  
  117. $users = DB::table('sizes')
  118. ->crossJoin('colours')
  119. ->get();
  120. 1
  121. 2
  122. 3
  123. 高级连接
  124.  
  125. $result = DB::table('employees')->join('salaries',function($join){
  126. $join->on('employees.emp_no','=','salaries.emp_no')->where('employees.emp_no','>=','499980');
  127. })->get();
  128.  
  129. join函数的第二个参数为一个闭包,该闭包将会接收一个 JoinClause 对象用于指定 join 子句约束。
  130.  
  131. 子查询连接
  132.  
  133. $salaryQ = DB::table('salaries')->where('emp_no','>=','499980');
  134. $result = DB::table('employees')->joinSub($salaryQ,'salaries',function($join){
  135. $join->on('employees.emp_no','=','salaries.emp_no');
  136. })->get();
  137. return $result;
  138.  
  139. 可以使用 joinSub、leftJoinSub 和 rightJoinSub 方法将查询和一个子查询进行连接,每个方法都接收三个参数 —— 子查询、表别名和定义关联字段的闭包
  140.  
  141. Union
  142. $emps = DB::table('employees')->whereRaw('emp_no between 499980 and 499990');
  143. $result = DB::table('employees')->whereRaw('emp_no > 499990')->union($emps1)->get();
  144.  
  145. Where 子句
  146. 简单where子句
  147.  
  148. //添加一个条件
  149. DB::table('employees')->where('emp_no','>=','499980');
  150. //添加多个条件,传二维数组
  151. DB::table('employees')->where([
  152. ['emp_no','>=','499980'],
  153. ['gender','=','F']
  154. ]);
  155.  
  156. or语句
  157.  
  158. DB::table('employees')->where('emp_no','>=','499980')->orWhere('emp_no','<','10')->get();
  159. 1
  160. whereBetween
  161.  
  162. DB::table('employees')->whereBetween('emp_no',[499980,499999])->get();
  163. 1
  164. whereNotBetween同理
  165.  
  166. whereIn,whereNotIn
  167.  
  168. DB::table('employees')->whereIn('emp_no',[11111,11112,11113])->get();
  169. 1
  170. whereNotIn同理
  171.  
  172. whereNull,whereNotNull
  173.  
  174. DB::table('employees')->whereNull('birth_date')->get();
  175. 1
  176. wherNotNull同理
  177.  
  178. whereDate / whereMonth / whereDay / whereYear / whereTime
  179.  
  180. orderBy()
  181. $result = DB::table('employees')->whereIn('emp_no',[11111,11112,11113])->orderBy('hire_date','asc','birth_date','asc')->get();
  182. 1
  183. groupBy(),having
  184. DB::table('salaries')->select('emp_no','salary')->groupBy('emp_no','salary')->having('emp_no','>','499990')->get();
  185. 1
  186. insert()
  187. DB::table('employees')->insert(['firtst_name'=>'Jack','last_name'=>'Ma']);
  188. DB::table('employees')->insert([
  189. ['firtst_name'=>'Jack','last_name'=>'Ma'],
  190. ['firtst_name'=>'Jack2','last_name'=>'Ma']
  191. ]);
  192.  
  193. 获取自增ID
  194.  
  195. $id = DB::table('employees')->insertGetId(['firtst_name'=>'Jack','last_name'=>'Ma']);
  196. 1
  197. update()
  198. DB::table('employees')->where('id',1)->update(['last_name'=>'Ma','gendger'=>'M']);
  199. 1
  200. delete()
  201. DB::table('employees')->where('id',1)->delete();
  202. 1
  203. Eloquent
  204. 定义模型
  205. $ php artisan make:model Employee
  206. 1
  207. 这将在项目中生成一个Employee.php,内容如下:
  208.  
  209. <?php
  210.  
  211. namespace App;
  212.  
  213. use Illuminate\Database\Eloquent\Model;
  214.  
  215. class Employee extends Model
  216. {
  217. //
  218. }
  219.  
  220. 此时Employee模型默认对应employees表(小写的模型类名复数格式)。
  221.  
  222. 模型成员变量
  223. $table:关联到模型的数据表
  224. $primaryKey:主键名(默认为id)
  225. $keyType:主键类型(默认为整形数据)
  226. $incrementing:主键是否自增(默认为true)
  227. $fillable:可以被赋值的属性,不能与$guarded同时使用
  228. $guarded:不会被赋值的属性,不能与$fillable同时使用
  229. 获取
  230. $emps = Employee::all();//返回表中所有数据
  231. $emps = Employee::where([['last_name','like','A%'],['gender','=','M']])->orderby('birth_date','asc')->limit(3)->get();//条件查询
  232.  
  233. 1
  234. 2
  235. 3
  236. 就是将Employee模型就是一个查询构建器,我们可以在模型上使用查询构建起的所有方法。
  237.  
  238. 插入
  239. public function store(Request $request){
  240. $emp = new Employee();
  241. $emp->first_name = $request->input('first_name');
  242. $emp->last_name = $request->input('last_name');
  243. $emp->birth_date = $request->input('birth_date');
  244. $emp->hire_date = date('Y-m-d',time());
  245. $emp->gender = $request->input('gender');
  246. var_dump($emp);
  247. $emp->save();
  248. 0
  249. 更新
  250. $emp = Employee::find($emp_no);//先查询
  251. $emp->first_name = $request->input('first_name');
  252. $emp->last_name = $request->input('last_name');
  253. $emp->birth_date = $request->input('birth_date');
  254. $emp->hire_date = $request->input('hire_date');
  255. $emp->gender = $request->input('gender');
  256. $emp->save();//更新到数据库
  257.  
  258. 批量更新:
  259.  
  260. Employee::where('emp_no','>','500000')->update(['hire_date'=>'2020-05-10']);
  261. 1
  262. 删除
  263. Employee::find(1)->delete();//按主键删除
  264. Employee::where('last_name','AAA')->delete();//批量删除
  265. Employee::destroy(1);//按主键删除
  266. Employee::destroy([1,2,3]);//批量删除
  267.  
  268. 软删除
  269. class Employee extends Model
  270. {
  271. use SoftDeletes;
  272.  
  273. /**
  274. * 应该被调整为日期的属性
  275. *
  276. * @var array
  277. */
  278. protected $dates = ['deleted_at'];
  279. }
  280.  
  281. 表中有deleted_at列,那么上面的配置将会软删除
  282.  
  283. 关联关系
  284. class Employee extends Model
  285. {
  286. // protected $table = 'employees_temp';
  287. protected $primaryKey = 'emp_no';
  288. public $timestamps = false;
  289. // 一对一,一个Employee关联一个salary
  290. public function salary(){
  291. return $this->hasOne('App\Salary','emp_no','emp_no');
  292. }
  293. // 一对多,一个Employee关联一个title
  294. public function titles(){
  295. return $this->hasMany('App\Title','emp_no','emp_no');
  296. }
  297. }
  298.  
  299. hasOne和hasMany的第二个参数是外键名,默认为方法名加_id后缀,第二个参数为主键名,或当前模型的关联字段名称。
  300.  
  301. $emp = Employee::find(1);
  302. $salary = $emp->salary;
  303. $titles = $emp->titles;
  304. 1
  305. 2
  306. 3
  307. 逆向
  308. class Salary extends Model
  309. {
  310. public function Employee(){
  311. return $this->belongsTo('App\Employee','emp_no','emp_no');
  312. }
  313. }
  314.  
  315. belongsTo第二个参数是外键名,默认为当前模型名加_id后缀,第三个参数为主键名,默认为id。
  316.  
  317. $salary = Salary::find(1);
  318. $emp = $salary->emplioyee;
  319.  
  320. 多对多
  321. class Employee extends Model
  322. {
  323. protected $primaryKey = 'emp_no';
  324. public $timestamps = false;
  325. //一个员工对应多个部门,一个部门有多个员工
  326. public function departments(){
  327. return $this->belongsToMany('App\Department','dept_emp','emp_no','dept_no');
  328. }
  329. }
  330. class Department extends Model
  331. {
  332. protected $primaryKey = 'dept_no';
  333. }

Laravel—数据库操作与Eloquent模型使用总结的更多相关文章

  1. Laravel 数据库操作之Eloquent ORM模型

    //模型中的相关代码 namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model{ //默认对 ...

  2. laravel 数据库操作

    1 配置信息 1.1配置目录: config/database.php 1.2配置多个数据库 //默认的数据库 'mysql' => [ 'driver' => 'mysql', 'hos ...

  3. Laravel 数据库操作 Eloquent ORM

    laravel 操作数据库一般都使用它的Eloquent ORM才操作 建立模型 <?php namespace App; use Illuminate\Database\Eloquent\Mo ...

  4. laravel 数据库操作之 DB facade & 查询构造器 & Eloquent ORM

    <?php namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class S ...

  5. Laravel数据库操作 Eloquent ORM

    模型首先在App目录下建立student的文件夹 里面放上 Student.php 且需要继承基类Model //允许批量赋值的字段// protected $fillable = ['name',' ...

  6. laravel数据库操作sql语句用Eloquent ORM来构造

    现在有查询语句: SELECT users.sNmame, users.iCreateTime, users_ext.iAge, users_ext.sSex FROM users LEFT JOIN ...

  7. [ Laravel 5.6 文档 ]laravel数据库操作分页(自定义分页实现和自定义分页样式)

    简介 在其他框架中,分页可能是件非常痛苦的事,Laravel 让这件事变得简单.易于上手.Laravel 的分页器与查询构建器和 Eloquent ORM 集成在一起,并开箱提供方便的.易于使用的.基 ...

  8. laravel 数据库操作(表、字段)

    1)创建表(make:migration create),例如创建 articles php artisan make:migration create_articles_table --create ...

  9. ThinkPHP 学习笔记 ( 四 ) 数据库操作之关联模型 ( RelationMondel ) 和高级模型 ( AdvModel )

    一.关联模型 ( RelationMondel ) 1.数据查询 ① HAS_ONE 查询 创建两张数据表评论表和文章表: tpk_comment , tpk_article .评论和文章的对应关系为 ...

随机推荐

  1. NSString为何要用copy修饰,而不是strong?

    NSString本身是无所谓的,但是如果一个 NSString 指针指向了一个 NSMutableString的内存空间的话,如果使用 strong 修饰的话,如果你在别处修改这个值的话,那么原来的值 ...

  2. Java使用DOM方式读写XML

    一.DOM读取 import ***; public class ReadXML { public static void main(String[] args) { try { //DOM Docu ...

  3. 导航控制器跳转时隐藏底部tabbar

    - (void)setting { // 跳转到设置界面 XMGSettingViewController *settingVc = [[XMGSettingViewController alloc] ...

  4. LeetCode随缘刷题之两数相加

    逐步解释,有说错的地方欢迎指正. package leetcode.day_12_03; /** * 给你两个非空 的链表,表示两个非负的整数.它们每位数字都是按照逆序的方式存储的,并且每个节点只能存 ...

  5. [GWCTF 2019]re3 wp

    [GWCTF 2019]re3 关键点:AES MD5 动态调试 smc自解密 gdb使用 跟进main函数 发现一个典型smc异或自解密 可以用idc脚本 或者python patch 或者动态调试 ...

  6. interface中setup_time和hold_time

    interface中的setup_time和hold_time input:约束input信号提前T时间采样,然后在时钟沿更新到input信号上. output:约束output信号,在时钟沿T时间后 ...

  7. CentOS7安装及配置 Zabbix全步骤,超详细教程

    服务器太多,还在不同的平台和账户,监控不便 整个 Zabbix 监控,开始吧 一.关闭防火墙并开机不启动 sudo setenforce 0 sudo sed -i "s/SELINUX=e ...

  8. Python中模块、类、函数、实例调用案例

    19 a = '我是模块中的变量a' 20 21 def hi(): 22 a = '我是函数里的变量a' 23 print('函数"hi"已经运行!') 24 25 class ...

  9. Kubernetes:更新与回滚

    Blog:博客园 个人 除了创建,Deployment 提供的另一个重要的功能就是更新应用,这是一个比创建复杂很多的过程.想象一下在日常交付中,在线升级是一个很常见的需求,同时应该尽量保证不能因为升级 ...

  10. ctf平台

    CTF靶场 蓝鲸安全:http://whalectf.xin bugku:https://ctf.bugku.com XCTF攻防世界:https://adworld.xctf.org.cn/ i春秋 ...