1 配置信息

1.1配置目录:
config/database.php
1.2配置多个数据库
//默认的数据库
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
//更多配置
], //可以创建更多的数据库
'mysql' => [
'driver' => 'mysql_2',
'host' => env('DB_HOST', '192.168.1.2'),
'port' => env('DB_PORT', '3306'),
//更多配置
],

2 使用DB门面进行基本操作

一旦你设置好了数据库连接,就可以使用 DB facade 来进行查找。DB facade 提供每个类型的查找方法:select、update、insert、delete、statement。
 
2.1增->
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
2.2删->
$deleted = DB::delete('delete from users');
返回值:删除的行数将会被返回
2.3改->
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
返回值:该方法会返回此声明所影响的行数
2.4查->
$users = DB::select('select * from users where active = ?', [1]);
返回值:方法总会返回结果的数组数据。数组中的每个结果都是一个 PHP StdClass 对象,这使你能够访问到结果的值:
访问方法:
foreach ($users as $user) {
echo $user->name;
}
2.5事务处理->
//自动
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
//手动(可配合try catch使用)
DB::beginTransaction();
if($someContion){
DB::rollback();
return false;
}
DB::commit();
2.6有时候一些数据库操作不应该返回任何参数。对于这种类型的操作,你可以在 DB facade 使用 statement 方法:
DB::statement('drop table users');

3 查询构造器

为什么要使用查询构造器?
1>因为数据库查询构造器提供了方便、流畅的接口,我们不需要再写原生的sql语句,通过查询构造器提供给我们的各种方法来创建及运行数据库查找。这能够满足我们大部分需要,且能在所有被支持的数据库系统中使用。
2>Laravel 的查询构造器使用 PDO 参数绑定,以保护你的应用程序不受数据库注入攻击。在传入字符串作为绑定前不需要先清理它们。
 
如何得到一个查询构造器:
依赖DB门面,使用它提供给我们的table方法,传入表名,即可获取该表的查询构建器,在此基础上我们可以使用强大的链式调用直到得到最终结果。

3.1 获取结果

3.1.1 从数据表中获取所有的数据列
$users = DB::table('users')->get();
返回值: 一个数组结果,其中每一个结果都是 PHP StdClass 对象的实例,可以将列作为属性访问每个列的值。
访问方法:
foreach ($users as $user) {
echo $user->name;
//操作的是对象的属性
}
3.1.2 从数据表中获取单个列或行
1>取出单行数据,使用first 方法。
$user = DB::table('users')->where('name', 'John')->first();
返回值:单个 StdClass 对象: 访问方法:echo $user->name;
 
2>从单行数据中取出单个值,使用 value 方法。
$email = DB::table('users')->where('name', 'John')->value('email');
返回值:直接返回字段的值:
 
3.1.3 从数据表中将结果切块
若你需要操作数千条数据库记录,则可考虑使用 chunk 方法。这个方法一次只取出一小「块」结果,并会将每个区块传给一个闭包进行处理。
例如,让我们将整个 user 数据表进行切块,每次处理 100 条记录:
DB::table('users')->chunk(100, function($users) {
foreach ($users as $user) {
//
}
});
你可以从闭包中返回 false,以停止对后续切块的处理:
DB::table('users')->chunk(100, function($users) {
// 处理记录…
return false;
});
3.1.4 获取字段值列表
若你想要获取一个包含单个字段值的数组,你可以使用pluck方法
$titles = DB::table('roles')->pluck('title'); 
返回值:在这个例子中,我们将取出 role 数据表 title 字段的数组:
使用方法:
foreach ($titles as $title) {
echo $title;
}
你也可以在返回的数组中指定自定义的键值字段:
$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
echo $title;
}

3.2 select的用法

3.2.1 指定一个 Select 子句
//指定字段
$users = DB::table('users')->select('name', 'email as user_email')->get();
//distinct 方法允许你强制让查找返回不重复的结果:
$users = DB::table('users')->distinct()->get();
//已有一个实例,希望在select 子句中再加入一个字段,则可以使用 addSelect 方法:
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
3.2.2 原始表达式
//DB::raw 方法可以防止注入
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();

3.3 join的用法

3.3.1 基本用法(inner join)
$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();
如果想用左连接或者右连接,则使用leftjoin,rightjoin替换join即可
3.3.2 高级的 Join 语法
你也可以指定更高级的 join 子句。让我们以传入一个闭包当作 join 方法的第二参数来作为开始。此闭包会接收 JoinClause 对象,让你可以在 join 子句上指定约束:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
若你想要在连接中使用「where」风格的子句,则可以在连接中使用 where 和 orWhere 方法。这些方法会比较字段和一个值,来代替两个字段的比较:
DB::table('users')
->join('contacts', function ($join) {
$join->on('users.id', '=', 'contacts.user_id')
->where('contacts.user_id', '>', 5);
})
->get();
这里要提一下如果闭包函数functiton(){}中5是个变量,我们需要传过去那么应该这样写
function ($join) use($num){ $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', $num);
如果没有use($num)外面的$num是没法传递到where子句的

3.4 where的用法

3.4.1 基本用法
$users = DB::table('users')->where('votes', '=', 100)->get();
$users = DB::table('users')->where('name', 'like', 'T%')->get();
$users = DB::table('users')->where('votes', 100)->get(); //省略了等号
$users = DB::table('users')->where('votes', '>', 100) ->orWhere('name', 'John')->get();
$users = DB::table('users')->whereBetween('votes', [1, 100])->get(); //一个字段的值介于两个值之间
$users = DB::table('users')->whereNotBetween('votes', [1, 100])->get(); //一个字段的值落在两个值之外
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get(); //字段的值包含在指定的数组之内
$users = DB::table('users')->whereNotIn('id', [1, 2, 3])->get(); //字段的值不包含在指定的数组之内
$users = DB::table('users')->whereNull('updated_at')->get(); //指定列的值为 NULL
$users = DB::table('users')->whereNotNull('updated_at')->get(); //一个列的值不为 NULL
3.4.2 高级用法
将约束分组
DB::table('users')
->where('name', '=', 'John')
->orWhere(function ($query) {
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
上面例子会将闭包传入 orWhere 方法,以告诉查询语句构造器开始一个约束分组。此闭包接收一个查询语句构造器的实例,你可用它来设置应包含在括号分组内的约束。上面的例子会生成以下 SQL:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')
3.5 orderBy,groupBy,having
//排序
$users = DB::table('users') ->orderBy('name', 'desc') ->get();
//随机排序
$randomUser = DB::table('users') ->inRandomOrder() ->first();
//分组
$users = DB::table('users') ->groupBy('account_id') ->having('account_id', '>', 100) ->get();
//havingRaw 方法可用来将原始字符串设置为 having 子句的值
$users = DB::table('orders') ->select('department', DB::raw('SUM(price) as total_sales')) ->groupBy('department') ->havingRaw('SUM(price) > 2500') ->get();
3.6 条件查询语句
可以使用方法 when 来构建条件查询语句,只有当 when 的第一次参数为 true 的话,匿名函数里的 where 语句才会被执行:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query) use ($role) {
return $query->where('role_id', $role);
})
->get();
3.7 insert的用法
//插入一组数据
DB::table('users')->insert( ['email' => 'john@example.com', 'votes' => 0] );
//插入多组数据
DB::table('users')->insert([ ['email' => 'taylor@example.com', 'votes' => 0], ['email' => 'dayle@example.com', 'votes' => 0] ]);
//若数据表有自动递增的 id,则可使用 insertGetId 方法来插入记录并获取其 ID:
$id = DB::table('users')->insertGetId( ['email' => 'john@example.com', 'votes' => 0] );
3.8 update的用法
DB::table('users') ->where('id', 1) ->update(['votes' => 1]);
3.9 delete
DB::table('users')->delete();
DB::table('users')->where('votes', '<', 100)->delete();
//若你希望截去整个数据表的所有数据列,并将自动递增 ID 重设为零,则可以使用 truncate 方法:
DB::table('users')->truncate();
3.10悲观锁定
查询语句构造器也包含一些可用以协助你在 select 语法上作「悲观锁定」的函数。若要以「共享锁」来运行语句,则可在查找上使用 sharedLock 方法。共享锁可避免选择的数据列被更改,直到事务被提交为止:
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
此外,你也可以使用 lockForUpdate 方法。「用以更新」锁可避免数据列被其它共享锁修改或选取:
DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

laravel 数据库操作的更多相关文章

  1. Laravel—数据库操作与Eloquent模型使用总结

    数据库操作 执行原生SQL //查询 $emp = DB::select('select * from employees where emp_no = 1'); $emp = DB::select( ...

  2. Laravel 数据库操作 Eloquent ORM

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

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

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

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

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

  5. laravel数据库操作

    一.配置文件路径:/.env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT= DB_DATABASE=test DB_USERNAME=root DB_P ...

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

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

  7. Laravel数据库操作的三种方式

    http://blog.csdn.net/zls986992484/article/details/52824962

  8. Laravel数据库操作 Eloquent ORM

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

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

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

随机推荐

  1. git如何在自动生成补丁时指定补丁名的起始编号

    答:使用选项--start-number,用法如下: git format-patch 1f43be --start-number=2 这样就可以生成起始编号为2的补丁名,类似0002-me.patc ...

  2. CodeForces 828E DNA Evolution(树状数组)题解

    题意:给你一个串k,进行两个操作: “1 a b”:把a位置的字母换成b “2 l r s”:求l到r有多少个字母和s匹配,匹配的条件是这样:从l开始无限循环s形成一个串ss,然后匹配ss和指定区间的 ...

  3. 2018-2019 Russia Open High School Programming Contest (Unrated, Online Mirror, ICPC Rules, Teams Preferred)

    前言 有一场下午的cf,很滋磁啊,然后又和dalao(见右面链接)组队打了,dalao直接带飞我啊. 这是一篇题解,也是一篇总结,当然,让我把所有的题目都写个题解是不可能的了. 按照开题顺序讲吧. 在 ...

  4. [WCF安全2]使用wsHttpBinding构建UserName授权的WCF应用程序,非SSL

    上一篇文章中介绍了如何使用basicHttpBinding构建UserName授权的WCF应用程序,本文将为您介绍如何使用wsHttpBinding构建非SSL的UserName安全授权的WCF应用程 ...

  5. ongene database

    http://ongene.bioinfo-minzhao.org/index.html

  6. python 堆栈

    class Node: #堆栈链结节点的声明 def __init__(self): self.data= #堆栈数据的声明 self.next=None #堆栈中用来指向下一个节点 top=None ...

  7. Phpstorm Alt+Enter 自动导入类

    很方便!!!能够自动提示哪些类没有自动加载!!!然后Alt+Enter进行安装!!!

  8. vs_u8前缀

    1.ZC: 个人测试下来,VS2015开始 支持 u8前缀. 2.What's New for Visual C++ in Visual Studio 2015 https://msdn.micros ...

  9. 微软Azure DevOps自动化部署

    1.准备一个https://hub.docker.com账号,申请一个免费的镜像仓库(免费账户可以申请一个) 创建docker远程镜像库 2.新建一个mvc的项目 给这个项目加上Dockerfile文 ...

  10. iTerm2的设置和Zsh.

    很好的说明文: https://xiaozhou.net/learn-the-command-line-iterm-and-zsh-2017-06-23.html iTerm2是Mac os用户使用的 ...