Laravel Eloquent firstOrFail 返回表中的所有记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25456930/
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
Laravel Eloquent firstOrFail returns all records in table
提问by davidxd33
I'm trying to retrieve a row in my eloquent model. What I want to do is first search to see if it exists or throw an exception. In the Laravel docs, it says I can use firstOrFail
or findOrFail
. The eloquent query is as follows:
我正在尝试在我的雄辩模型中检索一行。我想要做的是首先搜索它是否存在或抛出异常。在 Laravel 文档中,它说我可以使用firstOrFail
或findOrFail
。雄辩的查询如下:
Game::where('game', 'game-name')->firstOrFail()->remember(60)->get()
Game::where('game', 'game-name')->firstOrFail()->remember(60)->get()
This works for finding the record and throwing an exception if not found however it returns all rows as a result. What I would like to do is just return the row that I've searched for. I am not indexing by primary key in this example so findOrFail doesn't work.
这适用于查找记录并在未找到时抛出异常,但它会返回所有行作为结果。我想做的只是返回我搜索过的行。在此示例中,我没有按主键进行索引,因此 findOrFail 不起作用。
If I replace ->get()
with ->first()
all it does is return the first row in the table. It ignores the ::where()
.
如果我->get()
用->first()
它替换它所做的就是返回表中的第一行。它忽略::where()
.
EDIT:When I removed ->get()
and ->remember()
it returned the desired row however I still would like to cache the query but when I use ->remember()
and print_r on the result, the entire eloquent model is dumped.
编辑:当我删除->get()
并->remember()
返回所需的行但是我仍然想缓存查询但是当我->remember()
在结果上使用和 print_r 时,整个 eloquent 模型被转储。
EDIT2:All is resolved. I always confuse the place of ->remember()
. The correct way to do this is:
EDIT2:一切都解决了。我总是混淆 的位置->remember()
。正确的做法是:
Game::where('game', 'game-name')->remember(60)->firstOrFail()
Game::where('game', 'game-name')->remember(60)->firstOrFail()
采纳答案by davidxd33
All is resolved.
I always confuse the place of ->remember()
.
The correct way to do this is:
一切都解决了。
我总是混淆 的位置->remember()
。
正确的做法是:
Game::where('game', 'game-name')->remember(60)->firstOrFail()
回答by marcanuy
Wrong result seems to be cached, avoid using remember until you have the right query. If you use getit will return a Collection instance. findOrFailexpect an id as the first parameter. Get the first result from your query with firstand then check if it is empty to throw an Exception
错误的结果似乎被缓存,避免使用记住,直到你有正确的查询。如果您使用get它将返回一个 Collection 实例。 findOrFail期望 id 作为第一个参数。从查询获得的第一个结果第一,然后检查是否是空的抛出一个异常
Game::where('game', 'game-name')->first();