如何知道 Laravel 4 中的查询是否失败?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18424122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to know if a query fails in Laravel 4?
提问by Darwing
Im using Laravel 4 with MySQL and I want to know how to control possible errors when a record is inserted, updated or deleted in DB. For example, if I do an update as follows:
我在 MySQL 中使用 Laravel 4,我想知道在 DB 中插入、更新或删除记录时如何控制可能的错误。例如,如果我按如下方式进行更新:
DB::table('user')->where('id', $id)->update($userdata);
How could I know if that query fails? I thought of using a try-catch block to catch the exception and deal with it but I want to know whether there exists a Laravel specific method.
我怎么知道该查询是否失败?我想使用 try-catch 块来捕获异常并处理它,但我想知道是否存在 Laravel 特定方法。
回答by itachi
put it in a try catch block.
把它放在一个 try catch 块中。
try {
DB::table('user')->where('id', $id)->update($userdata);
}catch(\Exception $e){
//Do something when query fails.
}
moreover,
而且,
DB::insert()
returns boolean.
DB::insert()
返回布尔值。
DB::update()
returns boolean
DB::update()
返回布尔值
DB::delete()
returns boolean
DB::delete()
返回布尔值
DB::insertGetId()
return the last inserted id.
DB::insertGetId()
返回最后插入的 id。
You can write your follow up codes depending upon the value.
您可以根据值编写后续代码。
P.S.The above are not for errors but just to know whether your query affectedsome rows or not.
PS以上不是为了错误,而是为了知道您的查询是否影响了某些行。