Jan*_*ose 5 controller laravel
我有一个名为“items”的表和一个名为“ref_code”的 where 条件的输入。
$items = DB::table('items')
->where('ref_code','=', $request->ref_code)
->get(['id', 'ref_code', 'name','price']);
Run Code Online (Sandbox Code Playgroud)
但我似乎无法获取每一列的值。
我使用以下方法检查了查询构建器是否工作:
return $items;
Run Code Online (Sandbox Code Playgroud)
幸运的是,没有问题。
但是返回或获取单个值不适用于:
return $items->id
Run Code Online (Sandbox Code Playgroud)
我的语法错了吗?所有这些都在我的控制器中。
编辑:我试过了
dd($items);
Run Code Online (Sandbox Code Playgroud)
在返回之前,它向我展示了这个:
Collection {#325 ?
#items: array:1 [?
0 => {#322 ?}
]
}
Run Code Online (Sandbox Code Playgroud)
感谢您使用结果更新您的问题。看看你的调试结果。看起来像
array:1 [?
0 => {#322 ?}
]
Run Code Online (Sandbox Code Playgroud)
这意味着您的查询将返回一组数组,因为您正在使用 get()方法。soget()方法总是返回一个数组的集合。
为了避免这个问题,你必须使用first()method 而不是get().
请记住:当您想要获取单行时,您必须始终使用 first() 方法。
所以你的查询应该是这样的:
$items = DB::table('items')
->select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
Run Code Online (Sandbox Code Playgroud)
或者
$item = YourModelName::select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
Run Code Online (Sandbox Code Playgroud)
最后得到输出 $item->id、$item->ref_code 等的输出。
希望它会有所帮助。
参考资料: https : //laravel.com/docs/5.4/queries#retrieving-results