我有一张名为" 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
我的语法错了吗?所有这些都在我的控制器内。
编辑:我试过dd($items);
返回之前它向我展示了这个:
Collection {#325 ▼
#items: array:1 [▼
0 => {#322 ▶}
]
}
答案 0 :(得分:3)
感谢您使用结果更新您的问题。查看调试结果。它看起来像
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
答案 1 :(得分:1)
get()
会返回一个集合
$items = DB::table('items')
->where('ref_code','=', $request->ref_code)
->get(['id', 'ref_code', 'name','price']);
在上面的情况中,$items
将是一个集合,因此您需要遍历集合以访问属性
foreach ($items as $item) {
$item->price;
}
如果您需要返回模型实例,则可以使用方法first()
$items = DB::table('items')
->select('id', 'ref_code', 'name', 'price')
->where('ref_code','=', $request->ref_code)
->first();
并以
的形式访问属性$items->price;
答案 2 :(得分:0)
使用模型
试试$result = Model_name::->where('ref_code','=', $request->ref_code)
->first(['id', 'ref_code', 'name', 'price']);