Laravel Raw DB Insert Affected Rows

本秂侑毒 提交于 2019-12-31 04:42:17

问题


I'm using raw queries with laravel 4, is there a way to check affected rows on an insert? DB::getPdo()->rowCount(); gives me an "undefined method" error. Code is as follows:

$query = "INSERT IGNORE INTO table (id) VALUES (?)";
$doQuery = DB::insert($query, array($value));
if ($doQuery) {
    return DB::getPdo()->last();
} else {
    return 0;
}

If not, is there an easy way to figure out whether an insert was done or not without making it two queries?


回答1:


You can use this function:

int affectingStatement(string $query, array $bindings = array())

Run an SQL statement and get the number of rows affected.

Parameters

  • string $query
  • array $bindings

Return Value

  • int

This function is already documented for laravel 4.2 as well as for 5.4.

Note that insert() is an alias for statement() and will return a boolean. While the functions update() and delete() are aliases for affectingStatement(). So if you want to be funny and confuse the reviewers you could also write $rowCount = DB::delete("INSERT IGNORE ...", $bindings) - and it will work.




回答2:


Well I figured out a workaround that should be just as efficient - use INSERT INTO instead of INSERT IGNORE INTO and use try/catch.

   $query = "INSERT INTO table (id) VALUES (?)";
    try {
        DB::insert($query, array($value));
        return 1;
    } catch (\Exception $e) {
        return 0;
    }


来源:https://stackoverflow.com/questions/31466584/laravel-raw-db-insert-affected-rows

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