【问题标题】:Laravel: toSql function not displaying query correctlyLaravel:toSql 函数无法正确显示查询
【发布时间】:2020-09-24 12:01:58
【问题描述】:

我正在尝试使用这行代码在我的索引屏幕上停止查询:

dd(DB::table('members')->where('name', '=', 'Tycho')->toSql());

现在的问题是,当我在屏幕上显示查询时,我得到了这个:

"select * from `members` where `name` = ?"

这些代码行的最终目标是我可以保存离线查询并在应用程序在线时执行它们。除非有人对此有解决方案,否则我必须将查询保存在数据库中。

【问题讨论】:

    标签: sql laravel


    【解决方案1】:

    当 Laravel 使用 Prepared Statements 时,您会看到 ? 占位符。

    请参阅Ijas Ameenudeen's answer on another SO question,其中详细介绍了如何在 Eloquent 构建器上添加 toRawSql() 宏,它将用您提供给原始查询的绑定替换占位符。

    【讨论】:

      【解决方案2】:

      这是因为您使用的是toSql 方法,您可以使用getBindings 方法来获取值/绑定。

      单线:

      $query = DB::table('members')->where('name', '=', 'Tycho')->toSql();
      // will give the raw query with bindings.
      $sqlWithBindings = str_replace_array('?', $query->getBindings(), $query->toSql());
      
      

      【讨论】:

        【解决方案3】:

        你可以试试这个:

            DB::enableQueryLog();
            DB::table('members')->where('name', '=', 'Tycho')->get();
            echo "<pre>";
            print_r(DB::getQueryLog());
        

        【讨论】:

          猜你喜欢
          • 2015-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多