查询构建器不显示变量?

Query builder not display variable?

我运行这个代码:

$id = 1;
$email = 'email@gmail.com';

$user = DB::table('users')->where([
  ['id', '=', $id],
  ['email', '=', $email]
])->toSql();
dd($user);

但是查询生成器打印是:

select * from `users` where (`id` = ? and `email` = ?)

为什么不打印是:

select * from `users` where (`id` = 1 and `email` = email@gmail.com)

这就是 toSql() 方法的工作原理。它只显示您准备好的查询但不执行它。

要执行查询,请使用 或类似的方法:

$user = DB::table('users')->where([
    ['id', '=', $id],
    ['email', '=', $email]
])->first();

查询生成器插入字符代替值以保护您免受 sql 注入,然后他自己会根据需要为您设置值,您将得到最终结果,并且事实上,你在屏幕上显示的只是查看查询queries

查询生成器插入字符代替值以保护您免受 SQL Injections.I 相信@Дмитрий-Смирнов 很好地回答了您的查询。

而不是直接使用原始 SQL 使用模型,您可以 cut-down 您的代码行使用以下代码:

$id = 1;
$email = 'email@gmail.com';

$user = User::where('id',$id)
            ->where('email',$email)
            ->get();
dd($user);