【问题标题】:Laravel/Lumen: How to return a single value from the first record matching WHERE clauseLaravel/Lumen:如何从匹配 WHERE 子句的第一条记录返回单个值
【发布时间】:2017-03-10 04:44:09
【问题描述】:

我正在尝试从与 where 子句匹配的第一条记录中返回单个列值。在下面来自我的控制器的示例中,我将此结果定义为 $code。我可以获取第一条记录,也可以获取特定的列值,但不能同时获取。

第一条记录: $code = DB::table('codes')->where('redeemed', '0')->first();

单列值: $code = DB::table('code')->where('redeemed', '0')->value('code');

如何在一个请求中同时完成这两项操作?

【问题讨论】:

    标签: php laravel lumen


    【解决方案1】:

    你要找的是pluck

    DB::table('codes')->where('redeemed', 0)->pluck('code');
    

    【讨论】:

    • 但这并不限制返回的记录数。如何合并 ->first()?
    • 没关系,我明白了!谢谢! DB::table('code')->where('redeemed', 0)->pluck('code')->first()
    【解决方案2】:

    您可以使用select() 方法:

    DB::table('codes')->where('redeemed', '0')->select('code')->first();
    

    【讨论】:

      【解决方案3】:

      你的第二个例子:

      $code = DB::table('codes')->where('redeemed', '0')->value('code');
      

      这已经可以满足您的需求了。 value()方法调用first(),在方法的定义中可以看出:

      public function value($column)
      {
          $result = (array) $this->first([$column]); // <-- call to first on query
      
          return count($result) > 0 ? reset($result) : null;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-11-15
        • 2015-09-23
        • 2014-09-03
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2012-06-08
        • 2021-07-29
        • 1970-01-01
        相关资源
        最近更新 更多