如何在 Laravel 中返回单个对象而不是集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28985479/
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 return a single object instead of a collection in Laravel
提问by Lucien Dubois
I try to return a single objectinstead of a collection in Laravel. Actually this code works:
我尝试在Laravel 中返回单个对象而不是集合。实际上这段代码有效:
public function show($id)
{
$facture = Facture::where('id', '=', $id)->with('items')->with('client')->get();
return Response::json($facture[0]);
}
but I Would like to know if it's the right way to do it?
但我想知道这是否是正确的做法?
回答by lukasgeiter
While first()
works for any kind of query, when you are fetching a model by id find()
is the preferred method. Also you can combine the two with
calls:
虽然first()
适用于任何类型的查询,但当您通过 id 获取模型时,find()
是首选方法。你也可以结合这两个with
调用:
$facture = Facture::with('items', 'client')->find($id);
回答by Noman Ur Rehman
Here is the right code to get only a single object instead of a collection:
这是仅获取单个对象而不是集合的正确代码:
public function show($id)
{
$facture = Facture::where('id', '=', $id)->with('items')->with('client')->first();
return Response::json($facture);
}