【问题标题】:Query builder not display variable?查询生成器不显示变量?
【发布时间】:2018-08-05 02:52:25
【问题描述】:

我运行这段代码:

$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)

【问题讨论】:

    标签: mysql laravel query-builder


    【解决方案1】:

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

    要执行查询,请使用get(), find(), first() 或类似方法:

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

    【讨论】:

    • 我知道方法get()find()first(),但我的问题是查询生成器不打印select * from `users` where (`id` = 1 and `email` = email@gmail.com)而不是select * from `users` where (`id` = ? and `email` = ?)
    【解决方案2】:

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

    【讨论】:

    • 谢谢 :thumb: ,你有什么办法打印值吗?
    • 它不需要在屏幕上打印给你,它是一个特殊的安全机制,在我看来你不需要在代码中看到这个,它足以保持一些点在你的头,但要单独显示变量,例如,在数组中
    【解决方案3】:

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

    然后直接使用原始 SQL 使用模型,您可以使用以下代码减少您的代码行:

    $id = 1;
    $email = 'email@gmail.com';
    
    $user = User::where('id',$id)
                ->where('email',$email)
                ->get();
    dd($user);
    

    【讨论】:

    • 谢谢 :thumb:
    猜你喜欢
    • 1970-01-01
    • 2019-02-14
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多