user3494047
user3494047

Reputation: 1693

how to escape backslash inside of quote with mysql

I am using Laravel migrations to create/manage all of my database scripts and I have a migration for creating a trigger.

Here it is

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;'
);

The problem is when I run show triggers; I get:

*************************** 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 collation_connection: utf8_unicode_ci Database Collation: latin1_swedish_ci

As you can see, what mysql read is if NEW.votable_type = "AppComment" then instead of what I want: if NEW.votable_type = "App\Comment" then ... Anyone know how I can tell mysql to read the backslash?

EDIT: what worked was using three backslashes

Upvotes: 3

Views: 2610

Answers (2)

user3494047
user3494047

Reputation: 1693

if NEW.votable_type = "App\\\Comment" then works. I believe the reason that you need two is because mysql needs one backslash and laravel needs one. As per mysql documentation \\ will print \ . But I guess that what happens is that Laravel escapes the first backslash and mysql escapes the second. So you need 3.

Upvotes: 2

dotnetspark
dotnetspark

Reputation: 581

For the backslash to be considered you should double it. Therefore, "App\\\\Comment" should give you "App\Comment"

Upvotes: 2

Related Questions