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

微笑、不失礼 提交于 2019-12-22 20:44:49

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18449247/how-to-make-update-query-with-parameters-and-case-statement-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!