Laravel—数据库操作与Eloquent模型使用总结
- 数据库操作
- 执行原生SQL
- //查询
- $emp = DB::select('select * from employees where emp_no = 1');
- $emp = DB::select('select * from employees where emp_no = ? and gender = ?',[1,'M']);
- $emp = DB::select('select * from employees where emp_no = :empNo and gender = :gender',['empNo'=>1,'gender'=>'M']);
- //插入
- DB::insert('insert into employees(first_name,last_name) values(?,?,?)',['Jack','Ma']);
- //更新,返回受影响的行数
- $affected = DB::update('update employees set gender = ? where emp_no = ?',['M',123]);
- //删除,返回被删除的行数
- $deleted = DB::delete('delete from employees where first_name = ?',['Jack']);
- //运行通用语句,不返回任何值
- DB::statement('drop table employees');
- 事务
- //如果事务闭包中抛出异常,事务将会自动回滚;如果闭包执行成功,事务将会自动提交:
- DB::transaction(function(){
- DB::insert('insert into employees(first_name,last_name) values(?,?,?)',['Jack','Ma']);
- $affected = DB::update('update employees set gender = ? where emp_no = ?',['M',123]);
- });
- //手动开启事务
- DB::beginTransaction();
- //手动回滚
- DB::rollBack();
- //手动提交
- DB::commit();
- 查询构建器
- table()
- 通过DB门面的table()函数来获取一个查询构建器实例。
- get()
- $emps = DB::table('employees').get();
- 1
- 返回包含结果集额的Illuminate\Support\Collection,其中每一个结果都是 PHP 的 StdClass 对象实例
- first()
- $emp = DB::table('employees')->first();
- 1
- 从数据表中获取一行数据
- value()
- $values = DB::table('employees')->where('emp_no','>=',499995)->value('first_name');
- 1
- 只获取第一条结果的某一列的数据
- pluck()
- 与value类似,但是返回所有符合条件的记录列数组。
- chunk()
- DB::table('employees')->where('emp_no','>=',499980)->orderby('emp_no')->chunk(10,function($emps){
- foreach ($emps as $emp) {
- echo $emp->first_name. '<br>';
- }
- });
- 1
- 2
- 3
- 4
- 5
- 将查询结果分块在回调函数中进行处理。
- 聚合函数
- //count()
- $result = DB::table('employees')->where('emp_no','>=',499980)->count();
- //max()
- $result = DB::table('salaries')->max('salary');
- //min()
- $result = DB::table('salaries')->min('salary');
- //sum()
- $result = DB::table('salaries')->where('emp_no','>=',499980)->sum('salary');
- //avg()
- $result = DB::table('salaries')->where('emp_no','>=',499980)->avg('salary');
- exists()、doesntExist
- $result = DB::table('employees')->where('emp_no','=','500000')->exists();
- $result = DB::table('employees')->where('emp_no','=','500000')->doesntExist();
- 判断结果是否存在或不存在
- select(),andSelect()
- $result = DB::table('employees')->where('emp_no','>=','499980')->select('first_name','last_name')->get();
- //上面的查询等同于:
- $query = DB::table('employees')->where('emp_no','>=','499980')->select('first_name');
- $result = $query->andSelect('last_name')->get();
- 指定查询的列
- distinct()
- $result = DB::table('employees')->where('emp_no','>=','499980')->select('first_name','last_name')->distinct()->get();
- 1
- 过滤重复结果
- 原生语句
- DB::Raw()
- $result = DB::table('employees')->select(DB::raw('count(1) as num'))->where('emp_no','>=', 499980')->get();
- 1
- whereRaw()
- $result = DB::table('employees')->select(DB::raw('count(1) as num'))->whereRaw('emp_no>=?',[499980])->get();
- 1
- 此外还有orWhereRaw(),havingRaw(),orhavingRaw(),orderByRaw()
- Join
- join
- $result = DB::table('employees')->join('salaries','employees.emp_no','=','salaries.emp_no')->where('employees.emp_no','>=','499980')->get();
- 1
- leftJoin,rightJoin类似。
- crossJoin():生成一个笛卡尔积
- $users = DB::table('sizes')
- ->crossJoin('colours')
- ->get();
- 1
- 2
- 3
- 高级连接
- $result = DB::table('employees')->join('salaries',function($join){
- $join->on('employees.emp_no','=','salaries.emp_no')->where('employees.emp_no','>=','499980');
- })->get();
- join函数的第二个参数为一个闭包,该闭包将会接收一个 JoinClause 对象用于指定 join 子句约束。
- 子查询连接
- $salaryQ = DB::table('salaries')->where('emp_no','>=','499980');
- $result = DB::table('employees')->joinSub($salaryQ,'salaries',function($join){
- $join->on('employees.emp_no','=','salaries.emp_no');
- })->get();
- return $result;
- 可以使用 joinSub、leftJoinSub 和 rightJoinSub 方法将查询和一个子查询进行连接,每个方法都接收三个参数 —— 子查询、表别名和定义关联字段的闭包
- Union
- $emps = DB::table('employees')->whereRaw('emp_no between 499980 and 499990');
- $result = DB::table('employees')->whereRaw('emp_no > 499990')->union($emps1)->get();
- Where 子句
- 简单where子句
- //添加一个条件
- DB::table('employees')->where('emp_no','>=','499980');
- //添加多个条件,传二维数组
- DB::table('employees')->where([
- ['emp_no','>=','499980'],
- ['gender','=','F']
- ]);
- or语句
- DB::table('employees')->where('emp_no','>=','499980')->orWhere('emp_no','<','10')->get();
- 1
- whereBetween
- DB::table('employees')->whereBetween('emp_no',[499980,499999])->get();
- 1
- whereNotBetween同理
- whereIn,whereNotIn
- DB::table('employees')->whereIn('emp_no',[11111,11112,11113])->get();
- 1
- whereNotIn同理
- whereNull,whereNotNull
- DB::table('employees')->whereNull('birth_date')->get();
- 1
- wherNotNull同理
- whereDate / whereMonth / whereDay / whereYear / whereTime
- orderBy()
- $result = DB::table('employees')->whereIn('emp_no',[11111,11112,11113])->orderBy('hire_date','asc','birth_date','asc')->get();
- 1
- groupBy(),having
- DB::table('salaries')->select('emp_no','salary')->groupBy('emp_no','salary')->having('emp_no','>','499990')->get();
- 1
- insert()
- DB::table('employees')->insert(['firtst_name'=>'Jack','last_name'=>'Ma']);
- DB::table('employees')->insert([
- ['firtst_name'=>'Jack','last_name'=>'Ma'],
- ['firtst_name'=>'Jack2','last_name'=>'Ma']
- ]);
- 获取自增ID
- $id = DB::table('employees')->insertGetId(['firtst_name'=>'Jack','last_name'=>'Ma']);
- 1
- update()
- DB::table('employees')->where('id',1)->update(['last_name'=>'Ma','gendger'=>'M']);
- 1
- delete()
- DB::table('employees')->where('id',1)->delete();
- 1
- Eloquent
- 定义模型
- $ php artisan make:model Employee
- 1
- 这将在项目中生成一个Employee.php,内容如下:
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Employee extends Model
- {
- //
- }
- 此时Employee模型默认对应employees表(小写的模型类名复数格式)。
- 模型成员变量
- $table:关联到模型的数据表
- $primaryKey:主键名(默认为id)
- $keyType:主键类型(默认为整形数据)
- $incrementing:主键是否自增(默认为true)
- $fillable:可以被赋值的属性,不能与$guarded同时使用
- $guarded:不会被赋值的属性,不能与$fillable同时使用
- 获取
- $emps = Employee::all();//返回表中所有数据
- $emps = Employee::where([['last_name','like','A%'],['gender','=','M']])->orderby('birth_date','asc')->limit(3)->get();//条件查询
- 1
- 2
- 3
- 就是将Employee模型就是一个查询构建器,我们可以在模型上使用查询构建起的所有方法。
- 插入
- public function store(Request $request){
- $emp = new Employee();
- $emp->first_name = $request->input('first_name');
- $emp->last_name = $request->input('last_name');
- $emp->birth_date = $request->input('birth_date');
- $emp->hire_date = date('Y-m-d',time());
- $emp->gender = $request->input('gender');
- var_dump($emp);
- $emp->save();
- 0
- 更新
- $emp = Employee::find($emp_no);//先查询
- $emp->first_name = $request->input('first_name');
- $emp->last_name = $request->input('last_name');
- $emp->birth_date = $request->input('birth_date');
- $emp->hire_date = $request->input('hire_date');
- $emp->gender = $request->input('gender');
- $emp->save();//更新到数据库
- 批量更新:
- Employee::where('emp_no','>','500000')->update(['hire_date'=>'2020-05-10']);
- 1
- 删除
- Employee::find(1)->delete();//按主键删除
- Employee::where('last_name','AAA')->delete();//批量删除
- Employee::destroy(1);//按主键删除
- Employee::destroy([1,2,3]);//批量删除
- 软删除
- class Employee extends Model
- {
- use SoftDeletes;
- /**
- * 应该被调整为日期的属性
- *
- * @var array
- */
- protected $dates = ['deleted_at'];
- }
- 表中有deleted_at列,那么上面的配置将会软删除
- 关联关系
- class Employee extends Model
- {
- // protected $table = 'employees_temp';
- protected $primaryKey = 'emp_no';
- public $timestamps = false;
- // 一对一,一个Employee关联一个salary
- public function salary(){
- return $this->hasOne('App\Salary','emp_no','emp_no');
- }
- // 一对多,一个Employee关联一个title
- public function titles(){
- return $this->hasMany('App\Title','emp_no','emp_no');
- }
- }
- hasOne和hasMany的第二个参数是外键名,默认为方法名加_id后缀,第二个参数为主键名,或当前模型的关联字段名称。
- $emp = Employee::find(1);
- $salary = $emp->salary;
- $titles = $emp->titles;
- 1
- 2
- 3
- 逆向
- class Salary extends Model
- {
- public function Employee(){
- return $this->belongsTo('App\Employee','emp_no','emp_no');
- }
- }
- belongsTo第二个参数是外键名,默认为当前模型名加_id后缀,第三个参数为主键名,默认为id。
- $salary = Salary::find(1);
- $emp = $salary->emplioyee;
- 多对多
- class Employee extends Model
- {
- protected $primaryKey = 'emp_no';
- public $timestamps = false;
- //一个员工对应多个部门,一个部门有多个员工
- public function departments(){
- return $this->belongsToMany('App\Department','dept_emp','emp_no','dept_no');
- }
- }
- class Department extends Model
- {
- protected $primaryKey = 'dept_no';
- }
Laravel—数据库操作与Eloquent模型使用总结的更多相关文章
- Laravel 数据库操作之Eloquent ORM模型
//模型中的相关代码 namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model{ //默认对 ...
- laravel 数据库操作
1 配置信息 1.1配置目录: config/database.php 1.2配置多个数据库 //默认的数据库 'mysql' => [ 'driver' => 'mysql', 'hos ...
- Laravel 数据库操作 Eloquent ORM
laravel 操作数据库一般都使用它的Eloquent ORM才操作 建立模型 <?php namespace App; use Illuminate\Database\Eloquent\Mo ...
- laravel 数据库操作之 DB facade & 查询构造器 & Eloquent ORM
<?php namespace App\Http\Controllers; use App\Student; use Illuminate\Support\Facades\DB; class S ...
- Laravel数据库操作 Eloquent ORM
模型首先在App目录下建立student的文件夹 里面放上 Student.php 且需要继承基类Model //允许批量赋值的字段// protected $fillable = ['name',' ...
- laravel数据库操作sql语句用Eloquent ORM来构造
现在有查询语句: SELECT users.sNmame, users.iCreateTime, users_ext.iAge, users_ext.sSex FROM users LEFT JOIN ...
- [ Laravel 5.6 文档 ]laravel数据库操作分页(自定义分页实现和自定义分页样式)
简介 在其他框架中,分页可能是件非常痛苦的事,Laravel 让这件事变得简单.易于上手.Laravel 的分页器与查询构建器和 Eloquent ORM 集成在一起,并开箱提供方便的.易于使用的.基 ...
- laravel 数据库操作(表、字段)
1)创建表(make:migration create),例如创建 articles php artisan make:migration create_articles_table --create ...
- ThinkPHP 学习笔记 ( 四 ) 数据库操作之关联模型 ( RelationMondel ) 和高级模型 ( AdvModel )
一.关联模型 ( RelationMondel ) 1.数据查询 ① HAS_ONE 查询 创建两张数据表评论表和文章表: tpk_comment , tpk_article .评论和文章的对应关系为 ...
随机推荐
- NSString为何要用copy修饰,而不是strong?
NSString本身是无所谓的,但是如果一个 NSString 指针指向了一个 NSMutableString的内存空间的话,如果使用 strong 修饰的话,如果你在别处修改这个值的话,那么原来的值 ...
- Java使用DOM方式读写XML
一.DOM读取 import ***; public class ReadXML { public static void main(String[] args) { try { //DOM Docu ...
- 导航控制器跳转时隐藏底部tabbar
- (void)setting { // 跳转到设置界面 XMGSettingViewController *settingVc = [[XMGSettingViewController alloc] ...
- LeetCode随缘刷题之两数相加
逐步解释,有说错的地方欢迎指正. package leetcode.day_12_03; /** * 给你两个非空 的链表,表示两个非负的整数.它们每位数字都是按照逆序的方式存储的,并且每个节点只能存 ...
- [GWCTF 2019]re3 wp
[GWCTF 2019]re3 关键点:AES MD5 动态调试 smc自解密 gdb使用 跟进main函数 发现一个典型smc异或自解密 可以用idc脚本 或者python patch 或者动态调试 ...
- interface中setup_time和hold_time
interface中的setup_time和hold_time input:约束input信号提前T时间采样,然后在时钟沿更新到input信号上. output:约束output信号,在时钟沿T时间后 ...
- CentOS7安装及配置 Zabbix全步骤,超详细教程
服务器太多,还在不同的平台和账户,监控不便 整个 Zabbix 监控,开始吧 一.关闭防火墙并开机不启动 sudo setenforce 0 sudo sed -i "s/SELINUX=e ...
- Python中模块、类、函数、实例调用案例
19 a = '我是模块中的变量a' 20 21 def hi(): 22 a = '我是函数里的变量a' 23 print('函数"hi"已经运行!') 24 25 class ...
- Kubernetes:更新与回滚
Blog:博客园 个人 除了创建,Deployment 提供的另一个重要的功能就是更新应用,这是一个比创建复杂很多的过程.想象一下在日常交付中,在线升级是一个很常见的需求,同时应该尽量保证不能因为升级 ...
- ctf平台
CTF靶场 蓝鲸安全:http://whalectf.xin bugku:https://ctf.bugku.com XCTF攻防世界:https://adworld.xctf.org.cn/ i春秋 ...