Laravel如何使用查询生成器返回单列值 [英] Laravel how to return single column value using Query Builder

查看:75
本文介绍了Laravel如何使用查询生成器返回单列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SQL查询中的数据,在这里是我的代码来进一步说明:

I want to use the data from the SQL Query, to explain it further here is my code:

    $myquery = DB::table('attendances')->select('user_id')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();

    $myquery->user_id;

现在我希望我的$ myquery的值是USER_ID的值,如果我使用上述代码-$ myquery-> user_id,则会出现错误.

Now I want the value of my $myquery to be USER_ID's value, I get error if I used the Above code -$myquery->user_id;

推荐答案

自版本 5.1 pluck起,已弃用,因为 5.2 的含义完全不同(就像lists一样),所以请改用value方法.


您正在尝试获取数组的属性,因此很显然您会遇到错误.

As of version 5.1 pluck is deprecated, since 5.2 its meaning is completely different (as lists used to be), so use value method instead.


You're trying to get property of the array, so obviously you're getting error.

如果仅需要单个字段,则使用pluck(默认情况下返回单个值-字符串):

If you need single field only, then use pluck (which returns single value - string by default):

// let's assume user_id is 5

DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->pluck('user_id');  // "5"

当您需要整行时,然后first(返回stdObject):

When you need whole row, then first (which returns stdObject):

$att = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->first();

$att->user_id; // "5"
$att->any_other_column;

get是需要多个结果时(返回简单的stdObjects数组):

And get is when you want multiple results (which returns simple array of stdObjects):

$result = DB::table('attendances')
  ->where('date_only', '=', $newdate)
  ->orderBy('logon','asc')
  ->get();

$result; // array(0 => stdObject {..}, 1 => stdObject {..}, ...)
$result[0]->user_id; // "5"

这篇关于Laravel如何使用查询生成器返回单列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆