【问题标题】:how to escape backslash inside of quote with mysql如何使用mysql在引号内转义反斜杠
【发布时间】:2016-06-24 00:40:01
【问题描述】:

我正在使用 Laravel 迁移来创建/管理我的所有数据库脚本,并且我有一个用于创建触发器的迁移。

在这里

DB::unprepared(
    'create trigger update_points_aft_insert
        after insert on votes
        for each row
        begin
            declare u_id integer;
            if NEW.votable_type = "App\\Comment" then
                set u_id = (select user_id from comments where id = NEW.votable_id);
                update users set points=points+NEW.vote where id = u_id;
            end if;
    end;'
);

问题是当我运行show triggers; 我得到:

*************************** 1. row ***************************
         Trigger: update_points_aft_insert
           Event: INSERT
           Table: votes
       Statement: begin
                declare u_id integer;
                if NEW.votable_type = "AppComment" then
                    set u_id = (select user_id from comments where id = NEW.votable_id);
                    update users set points=points+NEW.vote where id = u_id;
                end if;
            end
          Timing: AFTER
         Created: NULL
        sql_mode: NO_ENGINE_SUBSTITUTION
         Definer: root@localhost

character_set_client: utf8 collat​​ion_connection:utf8_unicode_ci 数据库整理:latin1_swedish_ci

如您所见,mysql 读取的是if NEW.votable_type = "AppComment" then 而不是我想要的:if NEW.votable_type = "App\Comment" then ... 有谁知道我如何告诉 mysql 读取反斜杠?

编辑:有效的是使用三个反斜杠

【问题讨论】:

  • 你试过三引号if NEW.votable_type = """App\\Comment""" then
  • 现在试了一下,结果是mysql:if NEW.votable_type = ""AppComment"" then

标签: php mysql laravel laravel-5


【解决方案1】:

要考虑反斜杠,您应该将其加倍。因此,“App\\\\Comment”应该给你“App\Comment”

【讨论】:

  • OP,如果您的代码中从一开始就已经有App\\Comment 版本,为什么您立即接受了这个答案?
  • 说双倍我的意思是 4 个反斜杠。我已经更新了我的答案。感谢您的观察。
  • 我使用了 3 个反斜杠,而不是 4 个。使用 2 个反斜杠不起作用
  • 我用过 3 没用。那你为什么接受这个答案?
  • 当你最初写它的时候,我以为你用了三个。所以也许我误读了你的答案。但三个作品。
【解决方案2】:

if NEW.votable_type = "App\\\Comment" then 有效。我相信你需要两个的原因是因为 mysql 需要一个反斜杠而 laravel 需要一个。根据 mysql documentation \\ 将打印 \ 。但我猜想发生的事情是 Laravel 转义了第一个反斜杠,而 mysql 转义了第二个。所以你需要 3 个。

【讨论】:

  • 对问题中发布的代码为何不起作用以及您的解决方案为何起作用的简短解释可以帮助 OP 和未来的读者。您还可以添加文档链接以支持您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多