Laravel - 查询构造器


[ 从数据表中获取所有的数据列 ]

你可以使用 DBfacade 的 table 方法开始查询。这个 table方法针对查询表返回一个查询构造器实例,允许你在查询时链式调用更多约束,并使用 get 方法获取最终结果

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

get 方法会返回一个 Illuminate\Support\Collection结果,其中每个结果都是一个 PHP StdClass 对象的实例。您可以通过访问列中对象的属性访问每个列的值:

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

[ 一行数据 ]

使用 first方法,可以取出第一条数据

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

如果你不需要一整行数据,则可以使用 value 方法来从单条记录中取出单个值。此方法将直接返回字段的值:

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

[ 一列之值 ]

如果你想要获取一个包含单个字段值的集合,可以使用 pluck 方法。

$rider = DB::table('riders')->pluck('name');
foreach ($roles as $rider => $r_name) {
    echo $r_name;
}

[ 结果分块 ]

如果你需要操作数千条数据库记录,可以考虑使用 chunk方法。这个方法每次只取出一小块结果,并会将每个块传递给一个闭包处理。这个方法对于编写数千条记录的Artisan 命令是非常有用的。例如,让我们把 users表进行分块,每次操作 100 条数据:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

你可以从闭包中返回 false,以停止对后续分块的处理:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    // Process the records...

    return false;
});

[ 聚合函数 ]

查询构造器也支持各种聚合方法,如 countmaxminavgsum。你可以在创建查询后调用其中的任意一个方法

$rider = DB::table('riders');
$count = $rider->count();
$max = $rider->max('kick');
$min = $rider->min('kick');
$sum = $rider->sum('kick');
$avg = $rider->avg('kick');
echo $count."<br/>";
echo $max."<br/>";
echo $min."<br/>";
echo $sum."<br/>";
echo $avg."<br/>";

[ Select ]

当然,你并不会总是想从数据表中选出所有的字段。这时可使用 select 方法自定义一个 select 子句来查询指定的字段:

$rider = DB::table('riders')->select('name')->get();

distinct 方法允许你强制让查询返回不重复的结果:

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

如果你已有一个查询构造器实例,并且希望在现有的 select 子句中加入一个字段,则可以使用 addSelect 方法:

$rider = DB::table('riders')->select('name');

$users = $rider->addSelect('kick')->get();

[ 原始表达式 ]

有时候你可能需要在查询中使用原始表达式。这些表达式将会被当作字符串注入到查询中,所以要小心避免造成 SQL 注入攻击!要创建一个原始表达式,可以使用 DB::raw 方法:

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

[ Join ]

Inner Join

查询构造器也可以编写 join 语法。若要执行基本的「inner join」,你可以在查询构造器实例上使用 join 方法。传递给 join 方法的第一个参数是你要 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();
Left Join
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
Cross Join
$users = DB::table('sizes')
            ->crossJoin('colours')
            ->get();
高级使用
DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

把 join 方法的 第二个参数改成一个闭包函数。

可以使用多个 on ,和 orOn 。 on 就默认带 AND 了。还可以使用 where 和 or where 来做连接

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

[ Unions ]

查询构造器也提供了一个快捷的方法来「合并」 两个查询。例如,你可以先创建一个初始查询,并使用 union

方法将它与第二个查询进行合并:

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

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

也可使用 unionAll 方法,它和 union 方法有着相同的用法

[ WHERE子句 ]

查找 Kick力为5.5 的骑士 。我们可以看到,第一个参数是字段,第二个参数是对比条件,第三个是对比数值。

$rider = DB::table('riders')->where('kick', '=', 5.5)->get();

第二参数可以填写数据库支持的运算符, > , < , = , <> , >= , <= , like 等等

第三参数和原生写法一样, % (N个), * (全部) , _ (一个) 等等

使用数组写法来表示多个条件

$rider = DB::table('riders')->where([
        ['kick', '<', '5.5'],
        ['speed', '>=', '6.5'],
])->first();
OR语法

orWhere 方法接收和 where 方法相同的参数:

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

如果where 的第二个参数不填,会默认为 = 运算符

whereBetween 与 whereNotBetween

orwhereBetween 和 whereBetween 一样

$rider = DB::table('riders')
                ->whereBetween('kick',['6','6.8'])
                ->orwhereBetween('speed',['4.6','8'])
                ->get();

orwhereNotBetween 和 whereNotBetween

$rider = DB::table('riders')
                ->orwhereNotBetween ('speed',['4.6','8'])
                ->get();

whereIn 与 whereNotIn

当然也存在 orwhereIn 和 orwhereNotIn, 这里就不细说了

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

whereNull 与 whereNotNull

当然也存在 orwhereNull 和 orwhereNotNull, 这里就不细说了

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

whereDate / whereMonth / whereDay / whereYear

whereDate 方法比较某字段的值与指定的日期是否相等:

$users = DB::table('users')
                ->whereDate('created_at', '2016-12-31')
                ->get();

whereMonth 方法比较某字段的值是否与一年的某一个月份相等:

$users = DB::table('users')
                ->whereMonth('created_at', '12')
                ->get();

whereDay 方法比较某列的值是否与一月中的某一天相等:

$users = DB::table('users')
                ->whereDay('created_at', '31')
                ->get();

whereYear 方法比较某列的值是否与指定的年份相等:

$users = DB::table('users')
                ->whereYear('created_at', '2016')
                ->get();

whereColumn

whereColumn方法用来检测两个列的数据是否一致

$users = DB::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at']
                ])->get();

[ 参数分组 ]

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')
Where Exists 语法
DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();

exists 只返回true / false

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)
JSON 字段查询

Laravel 也支持查询 JSON 类型的字段。目前,本特性仅支持 MySQL 5.7+ 和 Postgres数据库。可以使用 -> 运算符来查询 JSON 列数据:

$users = DB::table('users')
                ->where('options->language', 'en')
                ->get();

$users = DB::table('users')
                ->where('preferences->dining->meal', 'salad')
                ->get();

[ OrderBy / GroupBy / Limit / Offset ]

orderby

第一个参数是要排序的字段,第二个是排序的方法,可以多个并接。

$users = DB::table('riders')
                ->orderBy('kick','desc')
                ->orderBy('speed','asc')
                ->get();
latest / oldest

latestoldest 方法允许你更容易的依据日期对查询结果排序。默认查询结果将依据 created_at 列。或者,你可以使用字段名称排序:

$user = DB::table('riders')
                ->latest('create_at')
                ->first();
//我的骑士表打错字了, create_at 没有D 。。。。, 刚好用来做演示

latest ->> desc, oldest ->> asc

inRandomOrder

inRandomOrder 方法可以将查询结果随机排序。例如,你可以使用这个方法获取一个随机用户:

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
groupBy / having / havingRaw

groupByhaving 方法可用来对查询结果进行分组。having 方法的用法和 where 方法类似:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

havingRaw 方法可以将一个原始的表达式设置为 having 子句的值。例如,我们能找出所有销售额超过 2,500 元的部门:

$users = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > 2500')
                ->get();
skip / take
$users = DB::table('users')->skip(10)->take(5)->get();
//兑换下来就是offset 和 limit
//你可以写成
$users = DB::table('users')->offset(10)->limit(5)->get();

[ 条件语句 ]

有时候,你希望某个值为 true 时才执行查询。例如,如果在传入请求中存在指定的输入值的时候才执行这个 where 语句。你可以使用 when 方法实现:

$rid = null;
$rid = Input::get('rid');
$rider = DB::table('riders')
                ->when($rid, function ($query) use ($rid) {
                    return $query->where('id', $rid);
                })
                ->get();
dd($rider);

你可能会把另一个闭包当作第三个参数传递给 when 方法。如果第一个参数的值为 false时,这个闭包将执行。为了说明如何使用此功能,我们将使用它配置默认排序的查询:

$sortBy = null;

$users = DB::table('users')
                ->when($sortBy, function ($query) use ($sortBy) {
                    return $query->orderBy($sortBy);
                }, function ($query) {
                    return $query->orderBy('name');
                })
                ->get();

[ Inserts ]

若数据表存在自增 id,则可以使用 insertGetId方法来插入记录并获取其 ID:

$id = DB::table('riders')->insertGetId(
    ['name' => 'ghost', 'kick' => 10, 'create_at' => '2017-06-16 01:27:00', 'update_at' => '2017-06-16 01:27:00']
);
//错误情况, 因为 name 是必填项目
$id = DB::table('riders')->insertGetId(
    ['kick' => '2.0', 'speed' => 10 ]
);

使用 DB Facade 处理增删改查,是没有自动处理的。所以一定要注意。

可以一次性插入一个数组中的东西,当然也要注意不能出错。

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0]
]);

[ Updates ]

update 方法和 insert 方法一样,接收含有字段及值的数组,其中包括要更新的字段。可以使用 where 子句来约束 update 查找

DB::table('users')
        ->where('id', 1)
        ->update(['votes' => 1]);
自增或自减

查询构造器也为指定字段提供了便利的自增和自减方法。

这两个方法都必须接收至少一个参数(要修改的字段)。也可选择传入第二个参数,用来控制字段应递增/递减的量:

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

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

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

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

您还可以指定要操作中更新其它字段:

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

[ Deletes ]

delete 前,还可使用 where 子句来约束 delete 语法:

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

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

如果你需要清空表,你可以使用 truncate 方法,这将删除所有行,并重置自动递增 ID 为零:

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

[ 悲观锁 ]

查询构造器也包含一些可以帮助你在 select 语法上实现「悲观锁定」的函数 。若要在查询中使用「共享锁」,可以使用 sharedLock 方法。共享锁可防止选中的数据列被篡改,直到事务被提交为止:

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

另外,你也可以使用 lockForUpdate 方法。使用「更新」锁可避免行被其它共享锁修改或选取:

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

results matching ""

    No results matching ""