未定义的属性:Illuminate \ Database \ Query \ Builder :: $ auth

时间:2018-07-04 15:32:09

标签: php mysql laravel

我有一个名为“ server_admins”和“ users”的数据库表。

server_admins表具有名为“ auth”的行

users表具有“ steam_id”和“ username”行

'auth'和'steam_id'具有相同的结果,例如:STEAM_0:0:113434

如何从“身份验证”转到“ steam_id”并获取用户名?

我正在这样尝试:

            $serveradmins = DB::table('server_admins')->get();
        $serveradmins->auth = DB::table('server_admins')->auth->get();
        $serveradmins->username = User::where('steam_id', '=', $serveradmins->auth)->first()->username;
        $this->pageView('servers::admins', ['serveradmins' => $serveradmins]);

但是出现错误:

Undefined property: Illuminate\Database\Query\Builder::$auth

抱歉,如果我真的很傻,我只是在学习laravel:)

1 个答案:

答案 0 :(得分:0)

我不确定您为什么要使用多个查询来获取已经拥有的内容,但是请记住,->get()返回的是Collection,而不是单个记录。将您的代码更改为:

$serverAdmin = DB::table('server_admins')->first();

此行:

$serveradmins->auth = DB::table('server_admins')->auth->get();

毫无道理;如果使用上述方法,则$serverAdmin->auth已经可用,因此调用另一个查询来获取它是多余的。其余的都很好:

$serveradmin->username = User::where('steam_id', '=', $serveradmins->auth)->first()->username;
$this->pageView('servers::admins', ['serveradmins' => $serveradmins]);

如果假设$serverAdmins是一个数组(或Collection),则需要进行一些循环:

$serveradmins = DB::table('server_admins')->get();
foreach($serverAdmins AS $serverAdmin){
    $serveradmin->username = User::where('steam_id', '=', $serveradmin->auth)->first()->username;
}
$this->pageView('servers::admins', ['serveradmins' => $serveradmins]);