Py学习  »  DATABASE

如何在控制器中从mysql访问数据属性

Aek Tachittanachote • 4 年前 • 621 次点击  

我学习了laravel框架,不知道如何访问控制器中的属性。

public function uuid(Request $request)
{
    if($request->get('uuid') == null) return abort(404);
    $uuid = $request->get('uuid');
    $users = DB::table('users')->select('*')->where('uuid', $uuid)->get();

    $result = array([
        'id' => $users['id'],
        'username' => $users['username'],
        'uuid' => $users['uuid'],
    ]);

    return view ('dashboard')->with('username', $result['username']);
}

在我的dashboard.blade.php中

{{$username}}

当我来到仪表盘时,它显示出这样的错误

错误异常(e_通知) 未定义索引:用户名

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39555
 
621 次点击  
文章 [ 4 ]  |  最新文章 4 年前
Mahfuz Ahmed
Reply   •   1 楼
Mahfuz Ahmed    4 年前

可能的解决方案的简短版本如下

public function uuid(Request $request)
{
    $user = User::select('username')->where('uuid', $request->uuid)->firstOrFail();

    return view ('dashboard')->with('username', $user->username);
}
Bilawal Awan
Reply   •   2 楼
Bilawal Awan    4 年前

您可以使用firstorfail();

 $users = DB::table('users')->select('*')->where('uuid', $uuid)->firstOrFail();

$result = array([
    'id' => $users->id,
    'username' => $users->username,
    'uuid' => $users->uuid,
]);

return view ('dashboard')->with('username', compact('username'));
Tharaka Dilshan
Reply   •   3 楼
Tharaka Dilshan    4 年前

$users 是用户的集合。所以您不能访问 $users['id'] ;

如果要从数据库中获取一个用户对象,则需要调用 first() 而不是 get()

可能的解决方案

$user = DB::table('users')->select('*')->where('uuid', $uuid)->first();

Dilip Hirapara
Reply   •   4 楼
Dilip Hirapara    4 年前

使用 第一() 而不是 获取() 您将获得对象,以便像这样访问数据。

$users = DB::table('users')->select('*')->where('uuid', $uuid)->first();

$result = array([
    'id' => $users->id,
    'username' => $users->username,
    'uuid' => $users->uuid,
]);

return view ('dashboard')->with('username', $result['username']);

现在找个方法来做。

 $user = DB::table('users')->select('*')->where('uuid', $uuid)->first();
 $username = '';
 if(!empty($user)){
    $username = $user->username 
 }

return view ('dashboard',compact('username'));