使用 cakephp,如何处理不返回结果的模型操作,以便我的视图不会中断?
在我的控制器中,我有可以返回空结果的模型操作。我已设置视图以使用 foreach 循环显示结果。但是,如果模型操作为空并且不返回任何结果,那么在我看来 foreach 循环就会中断。
就是这样的操作:
$match3 = $this->Draw->Match-> find('all',array('conditions'=>array('Match.draw_id'=>$id, 'Match.round_id'=> 1, 'Match.match_position' => 3)));
我需要在模型操作中添加什么才能返回 null?或者 null 是处理这个问题的最佳方法吗?
如果没有数据,那么我不想显示任何内容。
我确实尝试过这个,但得到了未定义的索引错误:
if (!$match3) 返回空值; 别的 返回$match3;
在处理空模型操作时是否有最佳实践?
非常感谢。 ——保罗
In my controller I have model operations that can return empty results. I've setup the view to display the results using a foreach loop. But if the model opertion is empty and returns no results then the foreach loop is breaking in my view.
This is the operation:
$match3 = $this->Draw->Match-> find('all',array('conditions'=>array('Match.draw_id'=>$id, 'Match.round_id'=> 1, 'Match.match_position' => 3)));
What do I need to add to the model operation to return null? Or is null the best way to handle this?
If there is no data then I don't want anything displayed.
I did try this but got an undefined index error:
if (!$match3)
return null;
else
return $match3;
Is there a best practice when it comes to handling empty model operations?
Much appreciated.
-Paul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
IMO,“最佳实践”不是 CakePHP 特定的。如果您的结果将其设置为空,则告知用户这一事实至关重要。这是一个简单的测试(在本例中为 Travis 所示的空数组)和一个简单的结果。在我看来,我通常会这样做:
IMO, the "best practice" isn't CakePHP-specific. If your result set it empty, it's critical to inform your users of that fact. It's a simple test (in this case for an empty array as indicated by Travis) and a simple result. I typically do it like this in my views:
如果您的查找操作没有结果,它将仅返回一个空数组。
在您看来,只需在输出该部分之前添加一些逻辑以确保 $match3 不是空数组即可。例如,在视图中
If your find operation has no results, it will just return an empty array.
In your view, just put some logic to make sure that $match3 isn't an empty array before you output that section. E.g., in the view
很大程度上取决于您的应用程序,以下响应可能是合适的:
或者
同样,这很大程度上取决于应用程序和相关操作,尤其是 404 不应该标准回应。在许多情况下,最好按照 抢。
Very much depending on your app, the following responses may be appropriate:
or
Again, this very much depends on the app and the action in question, especially a 404 should not be a standard response. In many cases it's probably best to handle it in the view as advised by Rob.