简介

Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends using either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four database systems:

Laravel让连接和使用数据库变得异常简单,对于不同数据库后台,使用原生SQL,或查询构建器,或Eloquent ORM都是如此,现在Laravel(5.1)支持四种数据系统

  • MySQL
  • Postgres
  • SQLite
  • SQL Server

#配置

Laravel makes connecting with databases and running queries extremely simple. The database configuration for your application is located at config/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.

By default, Laravel's sample environment configuration is ready to use with Laravel Homestead, which is a convenient virtual machine for doing Laravel development on your local machine. Of course, you are free to modify this configuration as needed for your local database.

Laravel使连接数据库和运行查询异常简单,应用的数据库配置文件是 config/database.php, 在文件里,你可以定义各种数据库连接配置, 以及制定那个连接应该被默认使用,文件中被提供了所有被支持的数据库系统连接的配置。

默认,Laravel的范例环境配置已经准备好用于Laravel Homestead, 它是一个方便的虚拟机,可以用于在你本机上开发Laravel应用,当然你可以自由改变这个配置用于你自己的数据库

读写分离配置

Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.

To see how read / write connections should be configured, let's look at this example:

有时候,你可能希望使用特懂数据库连接用于查询操作,同事使用另外的连接用于INSERT, UPDATE,以及 DELETE 操作。 LARAVEL让这些变的轻松简单,并确保你不论在使用原始查找,查找构建器,或者是Eloquent ORM使用的都是正确的连接。

下面来看看如何配置读取/写入连接, 让我们来看看以下的例子

'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [
'host' => '196.168.1.2'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],

Note that two keys have been added to the configuration array: read and write. Both of these keys have array values containing a single key: host. The rest of the database options for the read and write connections will be merged from the main mysql array.

So, we only need to place items in the read and write arrays if we wish to override the values in the main array. So, in this case, 192.168.1.1 will be used as the "read" connection, while 192.168.1.2 will be used as the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections.

注意我们加了两个键值到配置文件数组中: readwrite。 两个键值都包含了单一键值的数组:hostreadwrite 的其余数据库配置会从mysql 数组中合并。 所以,如果我们想要覆写配置值,只要将选项放入 readwrite 数组即可。 所以在上面的例子里, 192.168.1.1 将被用作「读取」连接,而 192.168.1.2 将被用作「写入」连接。数据库凭证、 前缀、字符编码配置、以及其他所有的配置会共用 mysql 数组里的配置。

运行原生SQL查询

Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select, update, insert, and statement.

一旦你配置好数据库连接你就可以通过DB facade执行查询, DB facade对不同数据操作提供了查询方法:select, update, insert, 和statement.

执行Select查找

To run a basic query, we can use the select method on the DB facade:

要运行一个基本查询,你可以使用DB facade 的 select方法

<?php

namespace App\Http\Controllers;

use DB;
use App\Http\Controllers\Controller; class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* @return Response
*/
public function index()
{
$users = DB::select('select * from users where active = ?', [1]); return view('user.index', ['users' => $users]);
}
}

The first argument passed to the select method is the raw SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.

The select method will always return an array of results. Each result within the array will be a PHP StdClass object, allowing you to access the values of the results:

第一个传入select方法的是一个原生SQL查询,第二个引数是需要绑定到查询语句的参数,通常,这些是where条件子句的值。 参数绑定防止了SQL注入的发生。

select方法会一直返回一个结果的数组,每个array中的结果都会是一个PHP StdClasss 对象, 允许你获得结果中的值。

foreach ($users as $user) {
echo $user->name;
}

使用名称绑定

Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:

相对于用?来表示参数绑定,你ikeyi运行一个使用命名绑定的查询

$results = DB::select('select * from users where id = :id', ['id' => 1]);

运行一个插入语法

To execute an insert statement, you may use the insert method on the DB facade. Like select, this method takes the raw SQL query as its first argument, and bindings as the second argument:

方法第一引数是查询语句,第二个引数是绑定

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

运行一个更新语法

The update method should be used to update existing records in the database. The number of rows affected by the statement will be returned by the method:

方法会返回被修改的行数

$affected = DB::update('update users set votes = 100 where name = ?', ['John']);

运行一个删除语法

The delete method should be used to delete records from the database. Like update, the number of rows deleted will be returned:

方法影响的行数被返回,就像更新操作一样。

$deleted = DB::delete('delete from users');

运行一个通用语句

Some database statements should not return any value. For these types of operations, you may use the statementmethod on the DB facade:

有些数据库操作不应该返回值,这些操作可以用statement方法来执行。

DB::statement('drop table users');

#监听查询事件

If you would like to receive each SQL query executed by your application, you may use the listen method. This method is useful for logging queries or debugging. You may register your query listener in a service provider:

你将收到每个SQL查询执行产生的事件, 你可以使用 listen 方法,这个方法对于产生日志和调试很有用处, 你可以在服务提供者登记你的查询监听器。

<?php

namespace App\Providers;

use DB;
use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
DB::listen(function($sql, $bindings, $time) {
//
});
} /**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}

数据库事务

To run a set of operations within a database transaction, you may use the transaction method on the DB facade. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. If the Closureexecutes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:

要在数据库事务里运行一组操作, 你可以使用DB facade的 transaction方法,如果一个异常在事务的闭包函数中抛出, 整个事务都会回滚, 如果事务执行成功, 这个事务会自动提交, 你i无需担心手动回滚或提交。

DB::transaction(function () {
DB::table('users')->update(['votes' => 1]); DB::table('posts')->delete();
});

手动使用事务

If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method on the DB facade:

你如果喜欢手动开始一个事务, 完全控制回滚和提交,你可以使用DB facade的 beginTransaction方法。

DB::beginTransaction();

You can rollback the transaction via the rollBack method:

你可以回滚这个事务用rollBack方法:

DB::rollBack();

Lastly, you can commit a transaction via the commit method:

最好你可以提交事务使用commit方法

DB::commit();

Note: 使用DB facade 的transaction方法也可以控制查询构建器和Eloquent ORM的事务.

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in yourconfig/database.php configuration file:

当使用多个连接时, 你可以用DB facade的connection方法获取每个连接, 每个传送到connection方法的名字应该对应在config/database.php配置文件中列出的名字。

$users = DB::connection('foo')->select(...);

You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:

你在connection实例上使用getPdo方法可以获取原生,下面的PDO实例,

$pdo = DB::connection()->getPdo();

Laravel5.1学习笔记15 数据库1 数据库使用入门的更多相关文章

  1. golang学习笔记16 beego orm 数据库操作

    golang学习笔记16 beego orm 数据库操作 beego ORM 是一个强大的 Go 语言 ORM 框架.她的灵感主要来自 Django ORM 和 SQLAlchemy. 目前该框架仍处 ...

  2. SQL反模式学习笔记15 分组

    目标:查询得到每组的max(或者min等其他聚合函数)值,并且得到这个行的其他字段 反模式:引用非分组列 单值规则:跟在Select之后的选择列表中的每一列,对于每个分组来说都必须返回且仅返回一直值. ...

  3. Ext.Net学习笔记15:Ext.Net GridPanel 汇总(Summary)用法

    Ext.Net学习笔记15:Ext.Net GridPanel 汇总(Summary)用法 Summary的用法和Group一样简单,分为两步: 启用Summary功能 在Feature标签内,添加如 ...

  4. 并发编程学习笔记(15)----Executor框架的使用

    Executor执行已提交的 Runnable 任务的对象.此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节.调度等)分离开来的方法.通常使用 Executor 而不是显式地创建 ...

  5. springMVC 学习笔记(一):springMVC 入门

    springMVC 学习笔记(一):spring 入门 什么是 springMVC springMVC 是 spring 框架的一个模块,springMVC 和 spring 无需通过中间整合层进行整 ...

  6. Django 学习笔记(七)数据库基本操作(增查改删)

    一.前期准备工作,创建数据库以及数据表,详情点击<Django 学习笔记(六)MySQL配置> 1.创建一个项目 2.创建一个应用 3.更改settings.py 4.更改models.p ...

  7. SQL server2005学习笔记(一)数据库的基本知识、基本操作(分离、脱机、收缩、备份、还原、附加)和基本语法

    在软件测试中,数据库是必备知识,假期闲里偷忙,整理了一点学习笔记,共同探讨. 阅读目录 基本知识 数据库发展史 数据库名词 SQL组成 基本操作 登录数据库操作 数据库远程连接操作 数据库分离操作 数 ...

  8. Android学习笔记(十七)——数据库操作(下)

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 这一次我们来试一试升级数据库,并进行数据库的CRUD操作,其中, C 代表添加(Create) ,R 代表查询 ...

  9. 【学习笔记】Y2-1-1 Oracle数据库基础

    Oracle 简介关系型(二维表)数据库 用来存储海量数据在大数据量的并发检索的情况下,性能要高于其他同类数据库产品一般运行环境是Linux和UnixOracle版本中的I(Internet) G(G ...

随机推荐

  1. __repr__()

    class A : def __init__(self,name): self.name=name #def __str__(self): # return '**%s**'%self.name de ...

  2. Leetcode 87.扰乱字符串

    扰乱字符串 给定一个字符串 s1,我们可以把它递归地分割成两个非空子字符串,从而将其表示为二叉树. 下图是字符串 s1 = "great" 的一种可能的表示形式. 在扰乱这个字符串 ...

  3. noip模拟赛 whzzt-Conscience

    分析:数据中并不存在无解的情况...... 每个摄像头都要覆盖尽可能多的点,按照y从小到大排序.对于每一列,只用判断第一个没有被观测到的就可以了,这个点必须要放摄像头,因为除了它自己没有其它的摄像头能 ...

  4. [UOJ48] 核聚变反应强度

    QUQ 思路 求出a1的所有约数,与a1.ai放入同一数组: 求出gcd(a1,ai): 枚举约数,得出ans; 代码实现 #include<cmath> #include<cstd ...

  5. [bzoj3668][Noi2014]起床困难综合症_暴力

    起床困难综合征 bzoj-3668 Noi-2014 题目大意:题目链接. 注释:略. 想法:Noi考这题...联赛T1难度.... 我们将每个门上的数二进制拆分. 发现:当前位的操作可能直接确定了当 ...

  6. codevs——2645 Spore

    2645 Spore  时间限制: 1 s  空间限制: 32000 KB  题目等级 : 钻石 Diamond 题解       题目描述 Description 某陈和某Y 最近对一个游戏着迷.那 ...

  7. SQL Server 2012内部原理及故障排除

    http://blog.csdn.net/burgess_liu/article/details/37900027

  8. android 程序猿跳槽须要注意哪些?

    我是一个工作3年多的android开发,因为公司和个人发展原因.打算跳槽! 这次跳槽又给我好好的上了一课!所以我自己反思总结了一下.然后整理出一下几点 程序猿打算跳槽的时候须要注意的几点. 一 先想好 ...

  9. iOS页面右滑返回的实现方法总结

    1.边缘触发的系统方法 ①系统返回按钮 self.navigationController.interactivePopGestureRecognizer.enabled = YES;  ②自定义返回 ...

  10. DCS实践干货:使用Redis实现分布式锁

    场景介绍 很多互联网场景(如商品秒杀,论坛回帖盖楼等),需要用加锁的方式,以对某种资源进行顺序访问控制.如果应用服务集群部署,则涉及到对分布式应用加锁.当前分布式加锁主要有三种方式:(磁盘)数据库.缓 ...