【问题标题】:Laravel Query Builder in LumenLumen 中的 Laravel 查询生成器
【发布时间】:2016-12-27 23:01:04
【问题描述】:

当我将 Laravel 的查询构建器用于我的带有 MySQL 数据库的 Lumen 应用程序时,它无法按预期工作。我用过:

$itemid = DB::table('table1')->where('UserID','=',1)->pluck('ID'); 

这只返回一个值。这里有什么错误?

【问题讨论】:

  • 该代码中没有任何内容表明您应该收到多少值。假设 UserID 是唯一的,那么您将始终拥有 1 条记录,而 pluck 将返回 1 条记录。这里没有任何错误,Laravel 和 Lumen 中的代码在 Eloquent / Query builder 中是相同的,所以错误在椅子上,而不是在电脑上。
  • 您期望有多少个值,为什么?

标签: laravel lumen


【解决方案1】:

试试

$itemid = DB::table('table1')->where('UserID','=',1)->get()->pluck('ID'); 

您可以在此处详细了解为什么在查询中使用 pluck 时会发生这种情况 Pluck together with first using Query builder

更新: 我忘记了 DB::table 返回数组,所以:

$items = DB::table('table1')->where('UserID','=',1)->get();
$itemsById = array_pluck($items, 'ID');

【讨论】:

  • Call to a member function pluck() on a non-object 这是结果
  • @Geding,从 5.3 开始它会返回集合。 Look here
【解决方案2】:

使用 first 而不是 get 作为 get 返回数组。

$itemid = DB::table('table1')->where('UserID','=',1)->first()->pluck('ID');

【讨论】:

    猜你喜欢
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2018-06-02
    • 2021-12-03
    • 2016-01-10
    • 2019-01-29
    相关资源
    最近更新 更多