如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:07:25  来源:igfitidea点击:

How to return a single object instead of a collection in Laravel

phplaravel

提问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 withcalls:

虽然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);
}