Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel,在Laravel中使用查询生成器value()方法时出现问题_Php_Laravel_Query Builder - Fatal编程技术网

Php Laravel,在Laravel中使用查询生成器value()方法时出现问题

Php Laravel,在Laravel中使用查询生成器value()方法时出现问题,php,laravel,query-builder,Php,Laravel,Query Builder,以下是用户表: 当我使用 $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=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;

非常感谢。我还注意到查询生成器的first()方法也随机选择第一行,如DB::table('user')->first('id')返回的是
first
只是告诉数据库您只想要行,这意味着,它将
LIMIT 1
添加到查询中。因此,查询结果的随机性不是来自Laravel,而是来自数据库
DB::table('user')->SQL中的第一个('id')
将是:
selectid fromuserslimit1。数据库决定返回哪一行(因为不存在强制它返回某一行的条件)。如果您特别想要第一行,您应该设置一个约束,如
WHERE id=?`或
ORDER BY id
。在Laravel中,它将是:
DB::table('user')->orderBy('id')->first('id')
DB::table('user')->WHERE('name','name')->first('id')
,这可能会对您有所帮助,这不是一个好主意您的取回id、name、,电子邮件单独编写一个查询,然后按对象读取一次使用$id=DB::table('user')->find('2')您确实以错误的方式获取数据
$id = 1;
$user = DB::table('users')->find($id);
$name = $user->name;
$email = $user->email;