Database API

Introduction

An improved Database API was recently added, which includes a QueryBuilder and a simple but powerful Model. Everything regarding this API is living within the namespace '\Database\' for isolation reasons.

To note that this new Database API doesn't replace any of the existing classes, the actual Core\Model andHelpers\Database remain untouched. The end-user can choose which Database API is used in their application, with the only condition to not use both of them simultaneously, which will duplicate the Database connections.

Basic Usage

Then new API is structured on three levels.

First, one of the levels, being a Database Connection, built on top of PDO, which is available both via getting an instance:

use Database\Connection;

$db = Connnection::getInstance();

$prefix = $db->getTablePrefix();

$data = $db->select("SELECT * FROM {$prefix}users");

and via a Facade which permit commands like:

use DB;

$prefix = DB::getTablePrefix();

$data = DB::select("SELECT * FROM {$prefix}users");

Commands for insert/update/delete are available.

To note that the Database\Connection fetches the data into objects or an array of objects.

The second level is represented by a very simple but powerful QueryBuilder, which permits commands like:

use DB;

$users = DB::table('users')->get();

$users = DB::table('users')->where('role', '=', 'admin')->get();

The third level is represented by a simple, yet powerful, Model, which uses the Database\Connection, instead of

Helpers\Database.

namespace App\Models;

use Database\Model;

class Users extends Model
{
protected $table = 'users'; protected $primaryKey = 'id'; public function __construct()
{
parent::__construct();
}
}

To note the two protected variables, which specify the Table name and Primary Key, which are mandatory to be configured, especially the Table name, the second one defaulting to 'id'.

A Database\Model is similar as usage with the Core\Model, but have the ability to transparently use the QueryBuilder methods, then permitting command like this:

use App\Models\Users;

$model = new Users();

$users = $model->where('role', '=', 'admin')->get();

Also, the Database\Model offer associated QueryBuilder instances, as following:

use App\Models\Users;

$model = new Users();

$query = $model->newQuery();

$users = $query->where('role', '=', 'admin')->get();

Selects

Retrieving All Rows From A Table

$users = DB::table('users')->get();

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

Retrieving A Single Row From A Table

$user = DB::table('users')->where('name', 'John')->first();

var_dump($user->name);

Retrieving A Single Column From A Row

$name = DB::table('users')->where('name', 'John')->pluck('name');

Retrieving A List Of Column Values

$roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

$roles = DB::table('roles')->lists('title', 'name');

Specifying A Select Clause

$users = DB::table('users')->select('name', 'email')->get();

$users = DB::table('users')->distinct()->get();

$users = DB::table('users')->select('name as user_name')->get();

Using Where Operators

$users = DB::table('users')->where('votes', '>', 100)->get();

Or Statements

$users = DB::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();

Using Where Between

$users = DB::table('users')
->whereBetween('votes', array(1, 100))->get();

Using Where Not Between

$users = DB::table('users')
->whereNotBetween('votes', array(1, 100))->get();

Using Where In With An Array

$users = DB::table('users')
->whereIn('id', array(1, 2, 3))->get(); $users = DB::table('users')
->whereNotIn('id', array(1, 2, 3))->get();

Using Where Null To Find Records With Unset Values

$users = DB::table('users')
->whereNull('updated_at')->get();

Order By, Group By, And Having

$users = DB::table('users')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();

Offset & Limit

$users = DB::table('users')->skip(10)->take(5)->get();

Joins

The query builder may also be used to write join statements. Take a look at the following examples:

Basic Join Statement

DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.id', 'contacts.phone', 'orders.price')
->get();

Left Join Statement

DB::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();

Aggregates

The query builder also provides a variety of aggregate methods, such as count, max, min, avg, and sum.

Using Aggregate Methods

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

$price = DB::table('orders')->min('price');

$price = DB::table('orders')->avg('price');

$total = DB::table('users')->sum('votes');

Raw Expressions

Sometimes you may need to use a raw expression in a query. These expressions will be injected into the query as strings, so be careful not to create any SQL injection points! To create a raw expression, you may use the DB::raw method:

Using A Raw Expression

$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();

Inserts

Inserting Records Into A Table

DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
);

Inserting Records Into A Table With An Auto-Incrementing ID

If the table has an auto-incrementing id, use insertGetId to insert a record and retrieve the id:

$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);

Note: When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named "id".

Inserting Multiple Records Into A Table

DB::table('users')->insert(array(
array('email' => 'daniel@example.com', 'votes' => 0),
array('email' => 'taylor@example.com', 'votes' => 0),
));

Updates

Updating Records In A Table

DB::table('users')
->where('id', 1)
->update(array('votes' => 1));

Incrementing or decrementing a value of a column

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);

You may also specify additional columns to update:

DB::table('users')->increment('votes', 1, array('name' => 'John'));

Deletes

Deleting Records In A Table

DB::table('users')->where('votes', '<', 100)->delete();

Deleting All Records From A Table

DB::table('users')->delete();

Truncating A Table

DB::table('users')->truncate();

Unions

The query builder also provides a quick way to "union" two queries together:

$first = DB::table('users')->whereNull('first_name');

$users = DB::table('users')->whereNull('last_name')->union($first)->get();

The unionAll method is also available, and has the same method signature as union.

Database API的更多相关文章

  1. PetaPoco轻量级ORM框架 - Database API 手册

    PetaPoco Database API #region IDisposable public void Dispose() #endregion #region Constructors publ ...

  2. HTML5教程之html 5 本地数据库(Web Sql Database)

    HTML5的Web SQL Databases(html5 本地数据库)的确很诱惑人,当你发现可以用与mysql查询一样的查询语句来操作本地数据库时,你会发现这东西挺有趣的.今天,我们一起来了解HTM ...

  3. HTML5 学习笔记(三)——本地存储(LocalStorage、SessionStorage、Web SQL Database)

    一.HTML4客户端存储 B/S架构的应用大量的信息存储在服务器端,客户端通过请求响应的方式从服务器获得数据,这样集中存储也会给服务器带来相应的压力,有些数据可以直接存储在客户端,传统的Web技术中会 ...

  4. Atitit.一个cms有多少少扩展点,多少api wordpress  cms有多少api。。扩展点

    Atitit.一个cms有多少少扩展点,多少api wordpress  cms有多少api..扩展点 1. Api分类 WordPress APIs1 1.1. 1 函数分类2 1.2. 函数api ...

  5. (转)HTML5开发学习(3):本地存储之Web Sql Database

    原文:http://www.cnblogs.com/xumingxiang/archive/2012/03/25/2416386.html HTML5开发学习(3):本地存储之Web Sql Data ...

  6. python27+django1.9添加api

    我们进入Python的交互 shell 并使用Django提供的API.要进入Python shell,使用python manage.py shell 使用这个而不是简单的输入"pytho ...

  7. HTML5的Web SQL Database

    本文将介绍 Web SQL Database 规范中定义的三个核心方法: openDatabase:这个方法使用现有数据库或新建数据库来创建数据库对象 transaction:这个方法允许我们根据情况 ...

  8. html 5 本地数据库(Web Sql Database)核心方法openDatabase、transaction、executeSql 详解

    Web SQL数据库API实际上不是HTML5规范的组成部分,而是单独的规范.它通过一套API来操纵客户端的数据库.Safari.Chrome. Firefox.Opera等主流浏览器都已经支持Web ...

  9. indexed database IndexedDB

    Indexed Database API 目的是提供一个可供javascript存储和检索对象,并且还能进行查询,搜索等数据库操作   设计为几乎完全异步,因此绝大部分操作都稍后执行,因此每次操作都应 ...

随机推荐

  1. Sql2005 全文索引详解

    1.前言 14.1  全文索引的介绍 14.2  全文索引中常用的术语 14.3  全文索引的体系结构 14.4  全文目录管理 14.4.1  创建全文目录 14.4.2  查看与修改全文目录 14 ...

  2. Codeforces 611D New Year and Ancient Prophecy dp+字符串比较

    这是CF Goodbye 2015 的D题,当时我想了一个n^3的dp算法,肯定不能过,然后听到学长后缀数组的n^2log(n)写法,仰慕 最后打完比赛看到了t神的n^2写法,简直膜拜,直接省去了后缀 ...

  3. ASP.Net MVC_DotNetZip简单使用方法,解决文件压缩的问题[转]

    准备工作: 在vs工具栏中找到NuGet   下载DotNetZip   现在就可以使用DotNetZip强大的类库了,在这里我给出一些简单的使用. ? 1 2 3 4 5 6 7 8 9 10 11 ...

  4. Jquery 操作xml 文档的方法

    需求: 页面上有两个下拉框,显示游戏大区 和游戏服务器,当游戏大区改变时,游戏服务器也跟着改变 界面部分html代码 <tr class="tkSigUser"> &l ...

  5. bzoj 1412 [ZJOI2009]狼和羊的故事(最小割)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1412 [题意] 在一个n*m的格子中,将羊和狼隔开的最小代价. [思路] 最小割. 由 ...

  6. 【暑假】[深入动态规划]UVa 10618 Tango Tango Insurrection

    UVa 10618 Tango Tango Insurrection 题目: Problem A: Tango Tango Insurrection You are attempting to lea ...

  7. HDU 1074 Doing Homework(状态压缩DP)

    题意:有n门课,每门课有截止时间和完成所需的时间,如果超过规定时间完成,每超过一天就会扣1分,问怎样安排做作业的顺序才能使得所扣的分最小 思路:二进制表示. #include<iostream& ...

  8. 部分常用Express方法详解

    app.set(name, value) 分配给name一个value,并将name作为app settings table的一个属性. 使用app.set('foo', true) 相当于调用 ap ...

  9. 题目1043:Day of Week(输入日期与当前日起天数差%7,在做相关星期调整)

    题目描述: We now use the Gregorian style of dating in Russia. The leap years are years with number divis ...

  10. 【spoj SEQN】【hdu 3439】Sequence

    题意: 给出n.m.k 求C(n,k)*H(n-k)%m的值 H(n-k)为错排公式 题解: 先算H(n-k) 计算H(n)有个通式: H(n)=(-1)^n+((-1)^(n-1))n+((-1)^ ...