Php 在laravel中使用原始查询从sql数据库获取特定列

Php 在laravel中使用原始查询从sql数据库获取特定列,php,laravel,laravel-query-builder,Php,Laravel,Laravel Query Builder,我有一个原始查询,它从Laravel中的数据库表中提取数据 $username = DB::table('hotspot_users') ->select('userName') ->where('assignedTo', '786')->get(); 我得到这些值:[{“用户名”:“kim”}] 但是我只想提取用户名“kim”本身,而不是一个数组。我尝试过这样做,但没有成功: $convert1=json_decode($username); $newuser

我有一个原始查询,它从Laravel中的数据库表中提取数据

 $username = DB::table('hotspot_users')
 ->select('userName')  
 ->where('assignedTo', '786')->get();
我得到这些值:
[{“用户名”:“kim”}]

但是我只想提取用户名“kim”本身,而不是一个数组。我尝试过这样做,但没有成功:

 $convert1=json_decode($username);
 $newusername=$convert1->userName; 
但我得到一个错误:试图获取非对象的属性“userName”


你知道我如何解决这个问题吗?

Hi
正如你提到的,这是一个数组
[{“userName”:“kim”}]

所以你有两个选择

首先,你先
First
而不是
get
$username=DB::table('hotspot\u users')
->选择('用户名')
->其中('assignedTo','786')->first();
$newusername=$convert1->userName;
其次,获取数组的第一个元素
$username=DB::table('hotspot\u users')
->选择('用户名')
->其中('assignedTo','786')->get();
$username=重置($username);
$convert1=json_解码($username);
$newusername=$convert1['userName'];

您得到的是作为php stdClass对象的
DB
的结果,因此您可以对其进行迭代并获得查询的每个变量。下面的代码可能会对您有所帮助

如果使用
get()

$data = DB::table('hotspot_users')
           ->where('assignedTo', '786')->select('userName')->get();

foreach ($data as $datum) {
    $result[] = $datum->userName;
}
$data = DB::table('hotspot_users')
            ->where('assignedTo', '786')->select('userName')->first()->userName;
如果使用
first()

$data = DB::table('hotspot_users')
           ->where('assignedTo', '786')->select('userName')->get();

foreach ($data as $datum) {
    $result[] = $datum->userName;
}
$data = DB::table('hotspot_users')
            ->where('assignedTo', '786')->select('userName')->first()->userName;

你可以这样做,而不是你正在做什么:

HotspotUser::where('assignedTo',786)->pull('userName');
现在,您将拥有一组名称;或者,如果您只想要第一个:

HotspotUser::where('assignedTo',786)->first()->用户名;

(我不确定该属性是否为
用户名
用户名
;您应该有简单的列名,以方便查询。)

您可以发布查询结果吗?我已经指出;它的形式是[{“userName”:“kim”}]感谢第一个方法,我得到了一个错误,Json_decode()期望参数1为stringwith第二个我得到错误,尝试获取非对象的属性“userName”,我不知道我做错了什么,我更新了这两个,你能再试一次并说出结果吗?谢谢,它现在起作用了,不客气,朋友:)