如何使用 Laravel Fluent 更新查询并使用 db::raw?


如果要在流利查询生成器中测试或使用一些任意字符串,可以使用 db::raw。

要使用 db::raw,必须使用 DB 虚类 −

use Illuminate\Support\Facades\DB;

以下是一些演示如何使用 DB:raw(). 的示例。

示例 1

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { DB::table('users') ->where('id', 2) ->update(['name' =>DB::raw("'Heena Khan'")]); $user = DB::table('users')->find(2); print_r($user); } }

由于我们要将字符串传递给 name,因此我们使用如下所示的 DB::raw 中的字符串 −

update(['name' =>DB::raw("'Heena Khan'")]);

输出

以上代码的输出为 −

stdClass Object(
   [id] => 2
   [name] => Heena Khan
   [email] => [email protected]
   [email_verified_at] =>
   [password] => hkGekGafje
   [remember_token] =>
   [created_at] =>
   [updated_at] =>
)

示例 2

另一个示例是在 DB::update 中使用DB::raw(),如下所示 −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { $name = '"Seema"'; $test = DB::update(DB::raw('UPDATE users SET name='.$name.' WHERE id =3')); $user = DB::table('users')->find(3); print_r($user); } }

输出

以上代码的输出如下 −

stdClass Object(
   [id] => 3
   [name] => Seema
   [email] => [email protected]
   [email_verified_at] =>
   [password] => pDqluHE2x8
   [remember_token] =>
   [created_at] =>
   [updated_at] =>
)

示例 3

我们使用DB::statement执行查询 −

<?php namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { $name = '"Neha Singh"'; $test = DB::statement(DB::raw('UPDATE users SET name='.$name.' WHERE id =4')); $user = DB::table('users')->find(4); print_r($user); } }

输出

以上代码的输出为 −

stdClass Object(
   [id] => 4
   [name] => Neha Singh
   [email] => [email protected]
   [email_verified_at] =>
   [password] => jyfM24HRSd
   [remember_token] =>
   [created_at] =>
   [updated_at] =>
)

示例 4

在以下示例中,将DB::raw用于 DB::select 中,以上代码的输出为显示如下 −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Str; use Illuminate\Support\Facades\DB; class UserController extends Controller{ public function index() { $name = '"Neha Singh"'; $test = DB::select(DB::raw('SELECT * FROM users WHERE id=1')); print_r($test); } }

输出

Array(
   [0] => stdClass Object(
      [id] => 1
      [name] => Siya Khan
      [email] => [email protected]
      [email_verified_at] =>
      [password] => yhka61wZeS
      [remember_token] =>
      [created_at] =>
      [updated_at] =>
   )
)

更新于: 30-Aug-2022

6K+ 浏览

开启你的 职业生涯

完成课程获得认证

开始
广告