Laravel Raw DB插入受影响的行 [英] Laravel Raw DB Insert Affected Rows
问题描述
我正在使用带有laravel 4的原始查询,有没有办法检查插入内容上受影响的行? DB::getPdo()->rowCount();
给我一个"undefined method" error
.代码如下:
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?
推荐答案
您可以使用此功能:
int affectingStatement (字符串$ query,数组$ bindings = array())
int affectingStatement(string $query, array $bindings = array())
运行一条SQL语句并获取受影响的行数.
Run an SQL statement and get the number of rows affected.
参数
- 字符串$ query
- 数组$ bindings
返回值
- int
This function is already documented for laravel 4.2 as well as for 5.4.
请注意,insert()
是statement()
的别名,并且将返回布尔值.而功能update()
和delete()
是affectingStatement()
的别名.因此,如果您想变得有趣并引起审阅者的困惑,您也可以写$rowCount = DB::delete("INSERT IGNORE ...", $bindings)
-它会起作用.
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.
这篇关于Laravel Raw DB插入受影响的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!