数据库入门之运行原始 SQL 查找

数据库入门之运行原始 SQL 查找

一旦你设置好了数据库连接,就可以使用 DB facade 来进行查找。DB facade 提供每个类型的查找方法:selectupdateinsertdeletestatement下面兄弟连帮你一一介绍。

运行一个 Select 查找#

DB facade 中使用 select 可以运行一个基本的查找:

<?php

namespace AppHttpControllers;

use DB;

use AppHttpControllersController;

class UserController extends Controller

{

    /**

     * 显示应用程序中所有用户的列表。

     *

     * @return Response

     */

    public function index()

    {

        $users = DB::select('select * from users where active = ?', [1]);

        return view('user.index', ['users' => $users]);

    }

}

传递给 select 方法的第一个参数是原始的 SQL 查找,而第二个参数是任何查找所需要的参数绑定。通常,这些都是 where 语句的限定值。参数绑定主要是为了防止 SQL 注入。

select 方法总会返回结果的数组数据。数组中的每个结果都是一个 PHP StdClass 对象,这使你能够访问到结果的值:

foreach ($users as $user) {

    echo $user->name;

}

使用命名绑定#

除了使用 ? 来表示你的参数绑定外,你也可以使用命名绑定运行查找:

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

运行 Insert#

若要运行 insert 语法,则可以在 DB facade 使用 insert 方法。如同 select 一样,这个方法的第一个参数是原始的 SQL 查找,第二个参数则是绑定:

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

运行 Update#

update 方法用于更新已经存在于数据库的记录。该方法会返回此声明所影响的行数:

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

运行 Delete#

delete 方法用于删除已经存在于数据库的记录。如同 update 一样,删除的行数将会被返回:

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

运行一般声明#

有时候一些数据库操作不应该返回任何参数。对于这种类型的操作,你可以在 DB facade 使用 statement 方法:

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

监听查找事件#

如果你希望能够监控到程序执行的每一条 SQL 语句,则可以使用 listen 方法。这个方法对于纪录查找跟调试将非常有用。你可以在 服务容器 中注册你的查找侦听器:

<?php

namespace AppProviders;

use DB;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider

{

    /**

     * 启动任何应用程序的服务。

     *

     * @return void

     */

    public function boot()

    {

        DB::listen(function($sql, $bindings, $time) {

            //

        });

    }

    /**

     * 注册一个服务提供者。

     *

     * @return void

     */

    public function register()

    {

        //

    }

}

原文地址:https://www.cnblogs.com/lampbrotherIT/p/5779170.html