我的查询是否成功? [英] Was my query successful?

查看:79
本文介绍了我的查询是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  User :: destroy(Input :: get('数据')); 

我需要测试上述操作是否成功,我该怎么办?



我尝试过:

  $ deleted = User ::破坏(输入::获得( '数据')); 

if(is_null($ deleted)){
App :: abort(404);
}

但无济于事。



这里推荐的做法是什么?

解决方案

如果你看看 Illuminate\Database\Eloquent\Model s destroy() 方法,你可以看到它返回删除的记录数。



所以最优雅的方式可能是: / p>

  $ deleted = User :: destroy(Input :: get('data')); 

if($ deleted === 0){
App :: abort(404);
}

然而,如果你不在乎严格的比较,你可以去:

  if(!User :: destroy(Input :: get('data'))
{
App :: abort(404);
}

这是因为0评估为false当不严格比较时,这也是对方法的评论说(1058-1060):


我们将在这里初始化一个计数我们将返回这个操作的删除总数
,然后开发人员可以将这个数字作为一个布尔值
类型的值来检索,或者获取这个记录数据的总计数,等等。


我建议您坚持强力比较,因为返回类型更清晰,但您可以随意选择任何您想要的。


I perform a variety of actions on my model, eg.

User::destroy(Input::get('data'));

I need to test whether the above operation was sucessful or not, how would I go about doing it?

I've tried:

$deleted = User::destroy(Input::get('data'));

if (is_null($deleted) ) {
    App::abort(404);
}

But to no avail.

What is recommended practice here?

解决方案

If you take a look at the Illuminate\Database\Eloquent\Models destroy() method you can see that it returns the number of records deleted.

So the most elegant way to go through it would probably be:

$deleted = User::destroy(Input::get('data'));

if ( $deleted === 0 ) {
    App::abort(404);
}

However if you don't care about strict comparison you could just go with:

if( ! User::destroy(Input::get('data') )
{
    App::abort(404);   
}

That works because 0 evaluates to false when not comparing strictly. That's also what the comments on the method say (1058-1060):

We'll initialize a count here so we will return the total number of deletes for the operation. The developers can then check this number as a boolean type value or get this total count of records deleted for logging, etc.

I would suggest you stick with strong comparison because the return type is just clearer, but you're free to choose whatever you want.

这篇关于我的查询是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆