拉拉维尔。使用查询生成器获取表的单列值

标签 laravel controller

我有一个名为“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/

相关文章:

laravel - 预加载三向数据透视表 Laravel

php - 如何在 Controller 上使用 if else 来实现搜索功能?

ruby-on-rails - RSPEC 测试 Controller 渲染 View ?

php - laravel 5 中的 Multi-Tenancy 应用程序?

javascript - 使用 JS 而不是 PHP 执行 Script 标签

objective-c - 在 cocoa 中使用绑定(bind)时,更改未反射(reflect)在 View 中

php - Phalcon php 中不能调用除 indexAction 以外的 indexController 操作

javafx 在适当的 Controller 类中使用 MainController 或其他 Controller 中的对象

java - 一个 Controller 用于不同的 View ?(MVC)

php - 我们可以在 php 中使用和操作 mysql 数据与 google 电子表格反之亦然吗?