Laravel,在Laravel

问题描述

这是用户表:

id  name                        email
1   Tia Fahey                   [email protected]
2   Ms. Sabrina Hahn III        [email protected]
3   Andrew Ullrich              [email protected]
4   Mrs. Marion Gutmann V       [email protected]
5   Letha Moen Jr.              [email protected]
6   Prof. ottilie Wilkinson IV  [email protected]

当我使用

$id=DB::table('users')->value('id');
$name=DB::table('users')->value('name');
$email=DB::table('users')->value('email');
echo $id."  ".$name."  ".$email;
// echo:
// 2  Tia Fahey  [email protected]

为什么它从第二行获取ID和电子邮件,而从第一行获取名称

解决方法

为什么它从第二行获取ID和电子邮件,而从第一行获取名称?

因为没有指定条件使选择随机。 您可以使用以下之一:

 // Returns directly the name column of the first row
$name = DB::table('users')->where('id',1)->value('name');

// Retrieves a collection containing only the name column of the first row
$name = DB::table('users')->orderBy('id')->first('name');

// Retrieves a collection containing only the name column of the last row
$name = DB::table('users')->orderBy('id','desc')->first('name');

// Retrieves a collection containing the name field for the row with id: $id.
$id = 1;
$name = DB::table('users')->find($id,'name');

如果要检索某一行的值,则无需多次查询数据库:在e上进行查询,然后访问列值,例如:

$id = 1;
$user = DB::table('users')->find($id);
$name = $user->name;
$email = $user->email;