我有一个名为“items”的表和一个名为“ref_code”的 where 条件的输入。
$items = DB::table('items')
->where('ref_code','=', $request->ref_code)
->get(['id', 'ref_code', 'name','price']);
但我似乎无法获取每一列的值。
我使用以下方法检查了查询构建器是否工作:
return $items;
幸运的是,没有问题。
但是返回或获取单个值不适用于:
return $items->id
我的语法错了吗?所有这些都在我的 Controller 中。
编辑:我试过了
dd($items);
在返回之前,它向我展示了这个:
Collection {#325 ▼
#items: array:1 [▼
0 => {#322 ▶}
]
}
最佳答案
感谢您使用结果更新您的问题。看看你的调试结果。看起来像
array:1 [▼
0 => {#322 ▶}
]
这意味着您的查询将返回一组数组,因为您使用的是
get()
方法。所以get()
方法总是返回一个数组的集合。为了避免这个问题,你必须使用
first()
方法而不是 get()
.记住 :当你想获得一行时,你必须使用 first() 方法。
所以你的查询应该是这样的:
$items = DB::table('items')
->select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
或者
$item = YourModelName::select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
最后得到类似 的输出
$item->id, $item->ref_code 等
希望它会有所帮助。
引用文献: https://laravel.com/docs/5.4/queries#retrieving-results
关于拉拉维尔。使用查询生成器获取表的单列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250772/