【问题标题】:Laravel. Get single column values of a table using Query Builder拉拉维尔。使用查询生成器获取表的单列值
【发布时间】:2017-07-22 04:44:20
【问题描述】:

我有一个名为“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 ▶}
  ]
}

【问题讨论】:

  • P.S:我使用 POST 方法从刀片中抛出 ref_code 输入。
  • $items 将是一个集合,因此您需要遍历 $items 以获取其属性
  • make dd($items) 并用结果更新问题

标签: laravel controller


【解决方案1】:

感谢您用结果更新您的问题。看看你的调试结果。看起来像

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

【讨论】:

  • 谢谢!这就像另一个答案一样神奇。大佬帮帮忙。 :)
  • 选择我提供的解决方案作为答案。所以它对我也有帮助。
【解决方案2】:

get() 会返回一个集合

$items = DB::table('items')
         ->where('ref_code','=', $request->ref_code)
         ->get(['id', 'ref_code', 'name','price']);

在上述情况下,$items 将是一个集合,因此您需要循环访问该集合以访问属性

foreach ($items as $item) {
    $item->price;
}

如果您需要返回 Model 实例,您可以改用 first() 方法

$items = DB::table('items')
             ->select('id', 'ref_code', 'name', 'price')
             ->where('ref_code','=', $request->ref_code)
             ->first();

并以

的身份访问属性
$items->price;

【讨论】:

    【解决方案3】:

    使用模型试试这个

    $result =  Model_name::->where('ref_code','=', $request->ref_code)
                           ->first(['id', 'ref_code', 'name', 'price']);
    

    【讨论】:

      猜你喜欢
      • 2018-01-01
      • 2019-03-08
      • 2020-06-24
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2015-04-13
      相关资源
      最近更新 更多