Laravel 能使用原生 SQL、查询构造器 和 Eloquent ORM 对数据库进行操作
目前laravel支持 下面4种数据库
MySQL
Postgres
SQLiteSQL
Server
配置数据库连接
数据库的配置文件放置在 config/database.php 文件中 .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=123456
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
原生sql语句操作
DB Facade 运行查询。 DB Facade 为每种类型的查询提供了方法: select 、 update 、 insert 、 delete 和 statement。
引入use Illuminate\Support\Facades\DB;
//插入数据 返回 true 或者false
DB::insert('insert into test (name,age) values (?,?)',['liming',23]);
//更新数据 返回影响的行数
DB::update('update test set age=? where id=?',[55,1]);
//查询 数据返回一个数组,数组中的每个结果都是一个 StdClass 对象
DB::select('select name,age from test where id=?',[2]);
//删除 返回影响的行数
DB::delete('delete from test where id=?',[1]);
查询构造器
插入插入一条数据
table 方法为给定的表返回一个查询构造器实例
//一维数组 key 和数据库 字段名 对应
$data = ['name'=>'liudehua','age'=>66];
$res = DB::table('test')->insert($data);
批量插入
二维数组
获取插入数据的id
$res = DB::table('test')->insertGetId($data);
更新数据$res = DB::table('test')->where('id',5)->update(['age'=>33]);
//多条件
$res = DB::table('test')->where(['id'=>7,'name'=>'liudehua'])->update(['age'=>33]);
$res = DB::table('test')->where('id','>',5)->update(['age'=>99]);
自增与自减自增 默认为自增 1
$res = DB::table('test')->where('id',4)->increment('age’);
自增 3
$res = DB::table('test')->where('id',4)->increment('age',3);
自减 默认为 1
$res = DB::table('test')->where('id',4)->decrement(‘age’);
自减 3
$res = DB::table('test')->where('id',4)->decrement('age',3);
删除
$res = DB::table('test')->where('id',5)->delete();
获取数据//获取多条数据 toArray() //结果集转数组
$res = DB::table('test')->get();
//获取一条数据 不加条件默认获取 第一条
$res = DB::table('test')->first();
//获取某个字段的值
$res = DB::table('test')->where('id',3)->value('age’);
//获取一列的值
$res = DB::table('test')->pluck('age’);
//获取指定字段的值
$res = DB::table('test')->select('name','age')->get();
聚合函数count, max, min, avg, 和 sum
$res = DB::table('test')->sum('age’);
$res = DB::table('test')->avg('age’);
$res = DB::table('test')->min('age’);
$res = DB::table('test')->max('age’);
$res = DB::table('test')->count();
where 语句
where 有3个参数
第一个参数是列名
第二个参数是任意一个数据库系统支持的运算符
第三个参数是该列要比较的值
第二个参数可以省 默认的 是 等号 运算符
whereBetween whereNotBetween whereIn / whereNotIn
$res = DB::table('test')->whereBetween('id',[4,7])->get();
$res = DB::table('test')->whereIn('id',[4,7])->get();
or 语句
orWhere 方法接受与 where 方法相同的参
$res = DB::table('test')->where('id','3')->orWhere('age',23)->get();
orderBy
$res = DB::table('test')->orderBy('id','desc')->get();
limit
$res = DB::table('test')->orderBy('id','desc')->limit(2)->get();
join 四个参数 内链接
$res = DB::table('test')->join('em ','test.id','=','em.test_id')->get();
leftJoin 左链接 和join用法相同
union
groupBy having….
事务
手动抛出 数据库的引擎 是innodb
三个过程
DB::beginTransaction();
DB::commit();
DB::rollback();
DB::beginTransaction();
try{
DB::table('test')->where('id',4)->decrement('age',4);
//throw new \Exception('出问题了');
DB::table('test')->where('id',6)->increment('age',4);
DB::commit();
}catch(\Exception $e){
echo $e->getMessage();
DB::rollback();
}
自动操作DB::transaction(function () {
DB::table('test')->where('id',4)->decrement('age',4);
DB::table('test')->where('id',222)->increment('age',4);
});
Eloquent ORM
Laravel 的 Eloquent ORM (Object Relational Mapping) 提供了漂亮、简洁的 ActiveRecord 实现来和数据库交互。每个数据库表都有一个对应的「模型」用来与该表交互。你可以通过模型查询数据表中的数据,并将新记录添加到数据表中。
模型定义规则:model
1 默认定义到 app目录下面 // 建议单独放到 Model的文件夹
2 所有模型都 要继承 基类 Model use Illuminate\Database\Eloquent\Model;
3 模型名Model.php
4 类名和文件名一致
UserController.php UserModel.php
模型与表一一对应
一个模型 一定 对应一个表
一个表 不一定要对应一个模型
UserModel.php 框架 默认会和 user_models 表对应
模型 添加 $table 属性 修改 表
protected $table='lampol_user';
默认情况下,Eloquent 会默认数据表中存在 created_at 和 updated_at 这两个字段。如果你不需要这两个字段,则需要在模型内将 $timestamps 属性设置为 false
// 时间默认存储的是 年月日 时分秒
public $timestamps = false;
//修改 存储时间格式 为字符串
protected $dateFormat = 'U’;
自定义用于存储时间戳的字段名
const CREATED_AT = ‘login_time’;
const UPDATED_AT = reg_time';
插入数据
类名::insert() 方法 和 DB 的用发基本一样 //返回bool
类名::insertGetId() 返回插入的id
save() 方法 //返回bool
类名::create() //返回实例模型
需要先在你的模型上指定 fillable 或 guarded 的属性
protected $fillable = [] 可以赋值的白名单
protected $guarded = [] 可以赋值的黑名单
更新数据
第一种
$user = self::find(1);
$user->name='liming';
$user->save();
Eloquent 也会假定每个数据表都有一个名为 id 的主键字段。你可以定义一个受保护的 $primaryKey 属性来覆盖这个约定。
protected $primaryKey =‘uid’; 修改主键名
第二种
self::where('uid',2)->update(['name'=>'xiaolizi']);
删除数据
第一种
$user = self::find(1);
return $user->delete();
第二种
$user = self::destroy(2); //主键
第三种
$user = self::where('uid',3)->delete();
查询数据返回数据 toArray()
//获取一条数据
$user = self::find(4); // 查询一条数据 主键默认 返回模型实例
$user = self::first()
//获取多条数据
$user = self::all()//查询所有数据 返回数据集
$user = self::get()//查询所有数据 返回数据集 //和查询构造器用法一样
模型关联
一对一
一对多
多对多
一个用户对应一个电话号码
一个用户对应多个收货地址
一个用户对应多个角色 一个角色对应多个用户
一对一
一个User 对应一个 Mobile
public function mobile(){
return $this->hasOne('App\Model\MobileModel’,’foregin_id’,’local_id’);
}
第一个参数 是 Mobile模型
第二个参数 关联的键 默认是 模型_id
第二个参数 是Mobile模型id
//使用
$mobile = self::find(4)->mobile->toArray();
$mobile = self::find(4)->mobile()->value('mobile');
一对多public function address(){
return $this->hasMany('App\Model\AddressModel','user_id');
}
hasMany 和 hasOne 用法一样
$mobile = self::find(4)->mobile
$mobile = self::find(4)->mobile()->value('mobile');
分页
查询构造器分页
$users = DB::table('lampol_user')->paginate(3);
ORM分页
self::paginate(4);
//简单的分页
simplePaginate(15)
视图展示
引入 bootstrap
return view('index',['page'=>$page]);
添加查询参数到分页
{{ $page->appends(['vip' => 'y'])->links() }}
表单验证
框架对表单传过来的数据内置了一套机制,进行数据的合法性验证。
使用 Validator
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data,$rules,$messages);
第一个参数是要验证的数据
第二个参数 是验证规则
第三个参数 错误提示信息 选填
$rules = [‘username’=>’required’];
$messages = [‘username.required’=>’用户名不能为空’];
判断验证是否通过
$validator->fails(); //不通过 返回true 否则返回false
$validator->passes(); //通过 返回true 否则返回 false
获取 错误信息$validator->errors()->first(); //获取第一个错误信息
$validator->errors()->all(); //获取所有错误信息
常用的几种验证规则
email //必须是email格式
numeric //必须是整数
ip //必须是ip地址
required //必须 不为空
url // 必须是url地址
max //字段的最大值
min //字段的最小值
between:min,max // 字段值的范围
自定义验证规则第一种
可以写到控制器 里
也可以写到 \app\Providers\AppServiceProvider.php boot方法 推荐
Validator::extend('mobile', function($attribute, $value, $parameters){
return preg_match('/^1[34578][0-9]{9}$/', $value);
});
要被验证的属性名称 $attribute、属性的值 $value、传入验证规则的参数数组 $parameter
//添加 错误提示信息
resources\lang\en\validation.php
第二种方式
在app下面创建一个Rules文件夹 然后创建一个验证文件 CheckMobile.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckMobile implements Rule{
public function passes($attribute, $value){
return preg_match('/^1[34578][0-9]{9}$/', $value);
}
public function message(){
return '电话好默哀好像不太对吧大兄弟';
}
}
使用
use App\Rules\CheckMobile;
$rules = ['phone'=>new CheckMobile]; // [‘phone’=>[‘require’, new CheckMobile]]
配置
配置文件有两个地方
第一 是在目录下面的 .env文件 //只放部分配置
第二个实在 config 下面的文件
.env文件主要存一些随环境变化 而变化的配置 不会被加到版本管理系统
读里面env的配置
用助手函数 env(配置名)
访问config目录下面的配置
助手函数 config(文件名.key);
助手函数
Laravel 包含各种各样的全局「辅助」PHP 函数,框架本身也大量地使用了这些功能;如果你觉得方便,你可以在你的应用中自由的使用它们。
关于路径助手函数
app_path() //获取app目录的全路径
base_path() //项目目录的路径
config_path() //配置文件 config全路径
database_path() //database目录全路径
public_path() //public 目录全路径
resource_path() //resource 目录全路径
storage_path() //storage 目录全路径
URLaction(‘UserController@index’) 获取 路由
asset(‘js/app.js’) //静态资源路径
secure_asset(‘js/app.js’) //https 静态资源路径
url(‘user’) //路由生成全路径url
secure_url(‘user’) //路由生成https路径
字符串处理camel_case('hello_world’); 函数将给定的值符传转换为「驼峰命名」helloWorld
kebab_case('helloWorld’);函数将给定的字符串转换为「短横线命名」hello-world
snake_case('helloWorld’); 函数将给定的字符串转换为「蛇形命名] hello_world
starts_with('hello world', 'hello’) //true
ends_with('hello world', 'd’) //true
str_limit('hello world', '3’) // hel...
str_random(4) //函数生成一个指定长度的随机字符串
数组处理array_add([‘name’=>‘liudehua’],‘age’,33) 添加键值到数组中
array_except(['name'=>'liudehua','age'=>33],['age’]) 从数组中删除给定的键/值对
array_has([‘name’=>‘liudehua’,‘age’=>33],[‘age’]) 判断数组是否有键
array_only([‘name’=>‘liudehua’,‘age’=>33],[‘age’]) 获取指定的键值
array_random([‘name’=>‘liudehua’,‘age’=>33]) 随机返回数组值
head([‘name’=>‘liudehua’,‘age’=>33]) 返回数组第一个值
last([‘name’=>‘liudehua’,‘age’=>33]) 返回数组最后一个值
其他助手app() 函数返回 服务容器 实例
back() 函数生成一个 重定向 HTTP 响应 到用户之前的位置:
config() 函数获取 配置 变量的值。
env() 函数获取 环境变量 的值或者返回默认值
cookie() 函数创建一个新的 cookie 实例
session 函数可以用来获取或者设置 Session 值
csrf_field() 函数生成包含 CSRF 令牌值的 HTML hidden 表单字段
csrf_token() 函数获取当前 CSRF 令牌的值
method_field() 函数生成一个 HTML hidden 表单字段
dd() 函数输出给定的值并结束脚本运行
dump() 函数打印给定的变量 不结束运行
request() 函数返回当前 请求 实例或者获取输入项
response 函数创建 响应 实例或者获取响应工厂实例
view() 函数获取一个 视图 实例
redirect() 函数返回一个 重定向 HTTP 响应
info() 函数将信息写入日志
logger() 函数可以将一个 debug 级别的消息写入到 日志 中
encrypt() 函数使用 Laravel 的 加密器 对给定的值进行加密
decrypt() 函数使用 Laravel 的 加密器 来解密给定的值
图片上传$img = $request->file(‘img’); //获取上传图片的信息
$img->isValid() //验证图片合法性
$img->getClientOriginalName(); //获取图片名
$img->getClientOriginalExtension(); //获取图片扩展名
$img->getClientMimeType(); //获取图片mime
$img->getClientSize(); //获取图片的大小
$img->move($img_path,$img_name) //开始上传
第一个图片存放目录
第二个图片名
验证码gd 库 以及 fileinfo扩展打开 https://packagist.org/
composer下载验证码
composer require mews/captcha
// 配置 添加下面的 config/app.php
'providers' => [
// ...
Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
// ...
'Captcha' => Mews\Captcha\Facades\Captcha::class,
]
//生成配置
php artisan vendor:publish
输出 captcha
Captcha::src()
验证验证码
$rules = ['cap' => 'required|captcha'];
$message = ['cap.captcha'=>'验证码不正确啊'];
$validator = Validator::make($request->input(), $rules,$message);
if($validator->fails()){
dd($validator->errors()->all());
}
日志配置文件在 config/logging.php
‘default’ => env(‘LOG_CHANNEL’, ‘stack’), //默认配置
single //一个日志文件
daily //每天一个日志文件
使用
use Illuminate\Support\Facades\Log;
Log::info('hello this is info');
Log::debug('hello this is debug');
Log::notice('hello this is notice');
Log::warning('hello this is warning');
Log::error('hello this is error');
Log::critical('hello this is critical');
Log::alert('hello this is alert');
Log::emergency('hello this is emergency’);
第二个参数 可以带数据
助手函数
logger(‘Debug message’); //debug 级别
logger()->error(‘error’);
artisanphp 命令添加到 环境变量
php astisan list 列出所有的参数
php artisan key:generate 重新生成 app key
php artisan cache:clear 清空缓存
php artisan config:clear 清空配置缓存
php artisan route:clear 清空配置缓存
php artisan view:clear 清空视图缓存
php artisan route:list 列出配置的路由
//创建控制器
php artisan make:controller OrderController
php artisan make:controller Admin/OrderController
php artisan make:controller TestController -r
创建模型
php artisan make:model TestModel
php artisan make:model Admin\TestModel
创建规则
php artisan make:rule CheckEmail
下面两种引入都可以
//use Illuminate\Support\Facades\Log;
use Log;
config/app.php alias 别名配置