Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Laravel中返回单个对象而不是集合_Php_Laravel - Fatal编程技术网

Php 如何在Laravel中返回单个对象而不是集合

Php 如何在Laravel中返回单个对象而不是集合,php,laravel,Php,Laravel,我尝试返回单个对象,而不是Laravel中的集合。实际上,该代码是有效的: public function show($id) { $facture = Facture::where('id', '=', $id)->with('items')->with('client')->get(); return Response::json($facture[0]); } 但我想知道这样做是否正确?以下是只获取单个对象而不是集合的正确代码: public funct

我尝试返回单个对象,而不是Laravel中的集合。实际上,该代码是有效的:

public function show($id)
{
    $facture = Facture::where('id', '=', $id)->with('items')->with('client')->get();
    return Response::json($facture[0]);
}

但我想知道这样做是否正确?

以下是只获取单个对象而不是集合的正确代码:

public function show($id)
{
    $facture = Facture::where('id', '=', $id)->with('items')->with('client')->first();
    return Response::json($facture);
}
虽然
first()
适用于任何类型的查询,但当您通过id获取模型时,首选方法是
find()
。您还可以将这两个
调用与
调用结合使用:

$facture = Facture::with('items', 'client')->find($id);

使用
first()
方法,而不是
get()
我刚刚尝试了不使用[0]的方法,它可以工作!请更新您的答案;)@是的,我注意到在你发表评论之前,我已经更新了答案。谢谢你指出。太好了,我喜欢这种紧凑的方式!find($id)比first()快吗?
find()
实际上只是为主键添加一个where条件(
where('id','=',$id)
),然后调用
first()
)。但是语法更好,您不必到处指定主键的名称:)
first
方法也可以正常工作,并返回单个对象而不是数组!