这是用户表:
id name email
1 Tia Fahey kathleen31@example.org
2 Ms. Sabrina Hahn III alejandra62@example.net
3 Andrew Ullrich germaine40@example.net
4 Mrs. Marion Gutmann V vita77@example.com
5 Letha Moen Jr. koepp.rigoberto@example.net
6 Prof. Ottilie Wilkinson IV tbode@example.com
当我使用时
$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 alejandra62@example.net
为什么它从第二行获取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;