Search code examples
phpmysqllaravellaravel-4fluent

How to make update query with parameters and CASE statement in Laravel 4


I'm trying to create mysql UPDATE query that will take parameters. In addition I want to append to the end of the field if the field isnt empty. For that I'm using CASE statement. Here's my query in doctrine (from silex):

$query = "UPDATE table SET filed = (
CASE WHEN field = ''
THEN :param1
ELSE concat(field, :param1)
END)
WHERE id=:param2";
$app['db']['test_db']->executeUpdate($sql, array('param1' => $user_text, 'param2' => $selected_id));

Now I want to convert it to fluent or raw query so I can use it in Laravel 4.

Here's my code:

$param1 = "String..."; // user string
$param2 = 45; // id
DB:connection('test_db')->statement("UPDATE table SET field =(
case
    WHEN field=''
    THEN $param1 
    ELSE concat(field, $param1)
END)
WHERE id=$param2");

When I execute this query in Laravel I see

Syntax error or access violation: 1064

Any help will be appreciated.


Solution

  • Try running it using raw():

    DB::statement(
        DB::raw(
                    "UPDATE table SET field =
                        (
                            CASE
                                WHEN field=''
                                THEN ?
                                ELSE concat(field, ?)
                            END
                        )
                        WHERE id=?"
        ),
    
        array($param1, $param1, $param2)
    );