数据库操作
执⾏原⽣SQL
1 //查询
2 $emp = DB::select('select * from employees where emp_no = 1');
3 $emp = DB::select('select * from employees where emp_no = ? and gender = ?',
[1,'M']);
4 $emp = DB::select('select * from employees where emp_no = :empNo and gender =
:gender',['empNo'=>1,'gender'=>'M']);
5 //插⼊
6 DB::insert('insert into employees(first_name,last_name) values(?,?,?)',
['Jack','Ma']);
7 //更新,返回受影响的⾏数
8 $affected = DB::update('update employees set gender = ? where emp_no = ?',
['M',123]);
9 //删除,返回被删除的⾏数
10 $deleted = DB::delete('delete from employees where first_name = ?',['Jack']);
11 //运⾏通⽤语句,不返回任何值
12 DB::statement('drop table employees');
事务
1 //如果事务闭包中抛出异常,事务将会⾃动回滚;如果闭包执⾏成功,事务将会⾃动提交:
2 DB::transaction(function(){
3 DB::insert('insert into employees(first_name,last_name) values(?,?,?)',
['Jack','Ma']);
4 $affected = DB::update('update employees set gender = ? where emp_no = ?',
['M',123]);
5 });
6 //⼿动开启事务
7 DB::beginTransaction();
8 //⼿动回滚
9 DB::rollBack();
10 //⼿动提交
11 DB::commit();查询构建器
table()
通过DB⻔⾯的table()函数来获取⼀个查询构建器实例。
get()
1 $emps = DB::table('employees').get();
返回包含结果集额的Illuminate\Support\Collection,其中每⼀个结果都是 PHP 的 StdClass 对象实
fifirst()
1 $emp = DB::table('employees')->first();
从数据表中获取⼀⾏数据
value()
1 $values = DB::table('employees')->where('emp_no','>=',499995)-
>value('first_name');
只获取第⼀条结果的某⼀列的数据
pluck()
与value类似,但是返回所有符合条件的记录列数组。
chunk()
1 DB::table('employees')->where('emp_no','>=',499980)->orderby('emp_no')-
>chunk(10,function($emps){
2 foreach ($emps as $emp) {
3 echo $emp->first_name. '<br>';
4 }
5 });
将查询结果分块在回调函数中进⾏处理。
聚合函数1 //count()
2 $result = DB::table('employees')->where('emp_no','>=',499980)->count();
3 //max()
4 $result = DB::table('salaries')->max('salary');
5 //min()
6 $result = DB::table('salaries')->min('salary');
7 //sum()
8 $result = DB::table('salaries')->where('emp_no','>=',499980)->sum('salary');
9 //avg()
10 $result = DB::table('salaries')->where('emp_no','>=',499980)->avg('salary');
exists()、doesntExist
1 $result = DB::table('employees')->where('emp_no','=','500000')->exists();
2 $result = DB::table('employees')->where('emp_no','=','500000')->doesntExist();
判断结果是否存在或不存在
select(),andSelect()
1 $result = DB::table('employees')->where('emp_no','>=','499980')-
>select('first_name','last_name')->get();
2 //上⾯的查询等同于:
3 $query = DB::table('employees')->where('emp_no','>=','499980')-
>select('first_name');
4 $result = $query->andSelect('last_name')->get();
指定查询的列
distinct()
1 $result = DB::table('employees')->where('emp_no','>=','499980')-
>select('first_name','last_name')->distinct()->get();
过滤重复结果
原⽣语句
1 DB::Raw()2 $result = DB::table('employees')->select(DB::raw('count(1) as num'))-
>where('emp_no','>=', 499980')->get();
whereRaw()
1 $result = DB::table('employees')->select(DB::raw('count(1) as num'))-
>whereRaw('emp_no>=?',[499980])->get();
此外还有orWhereRaw(),havingRaw(),orhavingRaw(),orderByRaw()
Join
join
1 $result = DB::table('employees')-
>join('salaries','employees.emp_no','=','salaries.emp_no')-
>where('employees.emp_no','>=','499980')->get();
leftJoin,rightJoin类似。
crossJoin():⽣成⼀个笛卡尔积
1 $users = DB::table('sizes')
2 ->crossJoin('colours')
3 ->get();
⾼级连接
1 $result = DB::table('employees')->join('salaries',function($join){
2 $join->on('employees.emp_no','=','salaries.emp_no')-
>where('employees.emp_no','>=','499980');
3 })->get();
join函数的第⼆个参数为⼀个闭包,该闭包将会接收⼀个 JoinClause 对象⽤于指定 join ⼦句约束。
⼦查询连接
1 $salaryQ = DB::table('salaries')->where('emp_no','>=','499980');
2 $result = DB::table('employees')->joinSub($salaryQ,'salaries',function($join){
3 $join->on('employees.emp_no','=','salaries.emp_no');
4 })->get();
5 return $result;可以使⽤ joinSub、leftJoinSub 和 rightJoinSub ⽅法将查询和⼀个⼦查询进⾏连接,每个⽅法都接收
三个参数 —— ⼦查询、表别名和定义关联字段的闭包
Union
1 $emps = DB::table('employees')->whereRaw('emp_no between 499980 and 499990');
2 $result = DB::table('employees')->whereRaw('emp_no > 499990')->union($emps1)-
>get();
Where ⼦句
简单where⼦句
1 //添加⼀个条件
2 DB::table('employees')->where('emp_no','>=','499980');
3 //添加多个条件,传⼆维数组
4 DB::table('employees')->where([
5 ['emp_no','>=','499980'],
6 ['gender','=','F']
7 ]);
or语句
1 DB::table('employees')->where('emp_no','>=','499980')-
>orWhere('emp_no','<','10')->get();
whereBetween
1 DB::table('employees')->whereBetween('emp_no',[499980,499999])->get();
whereNotBetween同理
whereIn,whereNotIn
1 DB::table('employees')->whereIn('emp_no',[11111,11112,11113])->get();
whereNotIn同理
whereNull,whereNotNull
1 DB::table('employees')->whereNull('birth_date')->get();
wherNotNull同理whereDate / whereMonth / whereDay / whereYear / whereTime
insert()
获取⾃增ID
update()
delete()
Eloquent
定义模型
这将在项⽬中⽣成⼀个Employee.php,内容如下:
orderBy()
$result = DB::table('employees')->whereIn('emp_no',[11111,11112,11113])-
>orderBy('hire_date','asc','birth_date','asc')->get();
1
2
groupBy(),having
DB::table('salaries')->select('emp_no','salary')->groupBy('emp_no','salary')-
>having('emp_no','>','499990')->get();
1
1 DB::table('employees')->insert(['firtst_name'=>'Jack','last_name'=>'Ma']);
2 DB::table('employees')->insert([
3 ['firtst_name'=>'Jack','last_name'=>'Ma'],
4 ['firtst_name'=>'Jack2','last_name'=>'Ma']
5 ]);
$id = DB::table('employees')-
>insertGetId(['firtst_name'=>'Jack','last_name'=>'Ma']);
1
DB::table('employees')->where('id',1)-
>update(['last_name'=>'Ma','gendger'=>'M']);
1
1 DB::table('employees')->where('id',1)->delete();
1 $ php artisan make:model Employee1 <?php
2 namespace App;
3 use Illuminate\Database\Eloquent\Model;
4 class Employee extends Model
5 {
6 //
7 }
此时Employee模型默认对应employees表(⼩写的模型类名复数格式)。
模型成员变量
$table:关联到模型的数据表
$primaryKey:主键名(默认为id)
$keyType:主键类型(默认为整形数据)
$incrementing:主键是否⾃增(默认为true)
$fifillable:可以被赋值的属性,不能与$guarded同时使⽤
$guarded:不会被赋值的属性,不能与$fifillable同时使⽤
获取
1 $emps = Employee::all();//返回表中所有数据
2 $emps = Employee::where([['last_name','like','A%'],['gender','=','M']])-
>orderby('birth_date','asc')->limit(3)->get();//条件查询
就是将Employee模型就是⼀个查询构建器,我们可以在模型上使⽤查询构建起的所有⽅法。
插⼊
1 public function store(Request $request){
2 $emp = new Employee();
3 $emp->first_name = $request->input('first_name');
4 $emp->last_name = $request->input('last_name');
5 $emp->birth_date = $request->input('birth_date');
6 $emp->hire_date = date('Y-m-d',time());
7 $emp->gender = $request->input('gender');
8 var_dump($emp);
9 $emp->save();
10 }
更新1 $emp = Employee::find($emp_no);//先查询
2 $emp->first_name = $request->input('first_name');
3 $emp->last_name = $request->input('last_name');
4 $emp->birth_date = $request->input('birth_date');
5 $emp->hire_date = $request->input('hire_date');
6 $emp->gender = $request->input('gender');
7 $emp->save();//更新到数据库
批量更新:
1 Employee::where('emp_no','>','500000')->update(['hire_date'=>'2020-05-10']);
删除
1 Employee::find(1)->delete();//按主键删除
2 Employee::where('last_name','AAA')->delete();//批量删除
3 Employee::destroy(1);//按主键删除
4 Employee::destroy([1,2,3]);//批量删除
软删除
1 class Employee extends Model
2 {
3 use SoftDeletes;
4 /**
5 * 应该被调整为⽇期的属性
6 *
7 * @var array
8 */
9 protected $dates = ['deleted_at'];
10 }
表中有deleted_at列,那么上⾯的配置将会软删除
关联关系
1 class Employee extends Model
2 {
3 // protected $table = 'employees_temp';
4 protected $primaryKey = 'emp_no';
5 public $timestamps = false;
6 // ⼀对⼀,⼀个Employee关联⼀个salary7 public function salary(){
8 return $this->hasOne('App\Salary','emp_no','emp_no');
9 }
10 // ⼀对多,⼀个Employee关联⼀个title
11 public function titles(){
12 return $this->hasMany('App\Title','emp_no','emp_no');
13 }
14 }
hasOne和hasMany的第⼆个参数是外键名,默认为⽅法名加_id后缀,第⼆个参数为主键名,或当前
模型的关联字段名称。
1 $emp = Employee::find(1);
2 $salary = $emp->salary;
3 $titles = $emp->titles;
逆向
1 class Salary extends Model
2 {
3 public function Employee(){
4 return $this->belongsTo('App\Employee','emp_no','emp_no');
5 }
6 }
belongsTo第⼆个参数是外键名,默认为当前模型名加_id后缀,第三个参数为主键名,默认为id。
1 $salary = Salary::find(1);
2 $emp = $salary->emplioyee;
多对多
1 class Employee extends Model
2 {
3 protected $primaryKey = 'emp_no';
4 public $timestamps = false;
5 //⼀个员⼯对应多个部⻔,⼀个部⻔有多个员⼯
6 public function departments(){
7 return $this->belongsToMany('App\Department','dept_emp','emp_no','dept_no');
8 }
9 }10 class Department extends Model
11 {
12 protected $primaryKey = 'dept_no';
13 }
除了employees和departments两张表之外,还有⼀张dept_emp关系表,在belongsToMany⽅法的第
⼆个参数中指定,不指定的话关系表名称默认为departments_employees(按⾸字⺟排序),
belongsToMany的第三个参数为关系表中关联employees表的外键名,默认为employee_id,第四个
参数为关系表中,关联departments表的外键,默认为department_id。
pivot:我们获取的每个Employee模型都会⾃动附上pivot属性,该属性是中间关系表模型。
关联插⼊、更新
1 $emp = Employee::find(1);
2 $emp->titles()->save(new Title(['title'=>'Manager']));//插⼊⼀条
3 $emp->titles()->saveMany([new Title(['title'=>'Manager']), new
Title(['title'=>'Developer']));

Laravel之数据库操作与Eloquent模型使用总结相关推荐

  1. laravel mysql增删改查_Laravel框架数据库操作的增删改三种方式 阿星小栈

    Laravel提供了3种操作数据库方式:DB facade(原始方式).查询构造器和Eloquent ORM. 数据库的配置文件在config目录下的database.php里.打开这个文件,找到my ...

  2. qt 不显示 mysql 数据表中的内容_qt 数据库操作总结

    整理一下 QT 操作数据库的一些要点,以备以后的查询学习(主要是操作 mysql ). 转载于:https://www.cnblogs.com/lsgxeva/p/7852102.html 首先,要查 ...

  3. qt 数据库操作总结

    整理一下 QT 操作数据库的一些要点,以备以后的查询学习(主要是操作 mysql ). 转载于:https://www.cnblogs.com/lsgxeva/p/7852102.html 首先,要查 ...

  4. php 查看 实例 的方法,php – 从Laravel 5.1中的通用数据库查询中获取Eloquent模型的实例...

    我有不同关系的模型.假设我的Entry模型属于供应商,所以通常我的模型文件中有一个supplier()方法. 到目前为止一切都那么好,当我有一些像Entry :: find(1) – >供应商这 ...

  5. laravel mysql sum,Laravel 数据库操作

    mysql DB 运行原始语句 select 查找 // 参数绑定 $users = DB::select('select * from users where active = ?', [1]); ...

  6. PHP利用分组查询groupby,Laravel 实现Eloquent模型分组查询并返回每个分组的数量 groupBy...

    Laravel 5.5 Linux mint 18 PHPStorm 最近刚玩Laravel,手册源码还没来得及看完就跃跃欲试做了个小项目,其中有个需求是分组查询数据库中的一个字段并返回每个分组中的数 ...

  7. Laravel 5.1 文档攻略 —— Eloquent:模型关系

    简介 其实大家都知道,数据表之间都是可以关联的,前面讲过了,Eloquent ORM是数据模型操作代替表操作,那么表的关联查询,在Eloquent这里也就是模型间的关联查询,这就是本章的主要内容: E ...

  8. Django模型之数据库操作-查询

    六.数据库操作-查询 6.1基础条件查询 1 基本查询 get查询单一结果,如果不存在会抛出模型类.DoesNotExist异常. all查询多个结果.[返回的所有结果是列表] count查询结果数量 ...

  9. Qt数据库操作(三) -- 使用SQL模型类

    文章目录 Qt数据库操作(三) -- 使用SQL模型类 1.SQL查询模型 2.SQL表格模型 3.关系表格模型 Qt数据库操作(三) – 使用SQL模型类 Qt 提供了3个高级的类来访问数据库,分别 ...

  10. ThinkPHP 数据库操作之数据表模型和基础模型 ( Model )

    一.定义数据表模型 1.模型映射 要测试数据库是否正常连接,最直接的办法就是在当前控制器中实例化数据表,然后使用 dump 函数输出,查看数据库的链接状态.代码: public function te ...

最新文章

  1. 计算机的网络通信软件的作用,网络协议软件的作用是什么
  2. 洛谷P1424小鱼的航程改进版
  3. 若依项目linux部署
  4. CentOS7 使用tab建补全命令
  5. git日常提交使用的命令行
  6. 平衡点 / 吊打XXX(洛谷-P1337)
  7. 0309随堂笔记 银行转帐功能 对向封装 1615278206
  8. 像素越多越好?像元的面积越小越好?
  9. Lua中调用C/C++函数 (转)
  10. Mybatis 异常(SQL 语法异常 ambiguous)
  11. IT江湖之怎样成为IT界的西门吹雪和独孤求败
  12. 第四周-C语言 圆柱体表面积计算
  13. java pdf添加页码_java itext pdf 怎么加页码
  14. Unity - AudioManager 给背景音乐、音效添加统一的音量管理
  15. Android之图片压缩
  16. 二维码可以包含多少个字符?
  17. c语言动态分配输出学生成绩,C语言之:结构体动态分配内存(利用结构体数组保存不超过10个学生的信息,每个学生的信息包括:学号、姓名和三门课(高数、物理和英语 )的成绩和平均分(整型)。)...
  18. Java怎么除以2_哪个更好的选项用于将整数除以2?
  19. php-fpm 重启失败,php-fpm启动失败
  20. BSGS 大步小步算法

热门文章

  1. SpringBoot图片上传报404无法回显,重启服务后又正常
  2. RGB与CMYK颜色模式调色原理
  3. 关闭Cortana小娜的几种方法(win10的搜索功能无法使用、黑屏/Cortana占用内存过高)
  4. java中的jsp是什么?
  5. html 制作魔方源代码,CSS3 3d环境实现立体 魔方效果代码
  6. 学 C++ ,能不能简单点?
  7. 步态情绪识别:STEP学习
  8. Failed to open /var/lib/samba/private/secrets.tdb
  9. 什么是PaaS?平台即服务介绍
  10. workman定时器使用