问题
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