没有不值得去解决的问题,也没有不值得去学习的技术!

Printed SQL From Laravel 6 Yields Different Results When Executed in MySQL 5.7

Decide to remove the ? in whereRaw and adjust it to raw SQL. Print the results of the SQL statement executed by the program, the count is 81

1. Print the SQL statement executed by the program, the result is as follows. As shown in Figure 1

Print the SQL statement executed by the program, the result is as follows
Figure 1
PHP

       $builder = ThemeAsset::select('updated_at', 'asset_key')
           ->where('theme_id', '=', $this->dbViewStorage->getThemeId())
           ->whereRaw('LOWER(asset_key) regexp ?', [strtolower($this->targetToRegex($target))]);

       $query = str_replace(array('?'), array('\'%s\''), $builder->toSql());
       $query = vsprintf($query, $builder->getBindings());
       dump($query);
       exit;

Plaintext

"select `updated_at`, `asset_key` from `theme_asset` where `theme_id` = 'theme' and LOWER(asset_key) regexp '^(assets|apps\.+\.+\assets)'"

2. Print the results of the SQL statement executed by the program, the count is 79. Array elements start from 0. As shown in Figure 2

Print the results of the SQL statement executed by the program, the count is 79. Array elements start from 0
Figure 2

3. Copy the printed SQL and execute it in MySQL 5.7. The count is 81. As shown in Figure 3

Copy the printed SQL and execute it in MySQL 5.7. The count is 81
Figure 3

4. Decide to remove the ? in whereRaw and adjust it to raw SQL. Print the results of the SQL statement executed by the program, the count is 81. As shown in Figure 4

Decide to remove the ? in whereRaw and adjust it to raw SQL. Print the results of the SQL statement executed by the program, the count is 81
Figure 4
PHP

$builder = ThemeAsset::select('updated_at', 'asset_key')
           ->where('theme_id', '=', $this->dbViewStorage->getThemeId())
           ->whereRaw('LOWER(asset_key) regexp \'^(assets|apps\.+\.+\assets)\'')

5. Keep the ? in whereRaw, need to use addslashes to escape \. Print the results of the SQL statement executed by the program, the count is 81. This meets expectations.

PHP

$assets = ThemeAsset::select('updated_at', 'asset_key')
            ->where('theme_id', '=', $this->dbViewStorage->getThemeId())
            ->whereRaw('LOWER(asset_key) regexp ?', [strtolower(addslashes($this->targetToRegex($target)))])
            ->get();

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系