Laravel Eloquent - 获得一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23925476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent - Get one Row
提问by Kousha
This might be a simple question, but I cannot figure this out. I am trying to get a user by email using:
这可能是一个简单的问题,但我无法弄清楚。我正在尝试使用以下方法通过电子邮件获取用户:
$user = User::whereEmail($email)->get();
But this is returning an array (of dimension 1) of $users. So If I want to get the name, I have to do $user[0]['first_name']
.
但这将返回 $users 的数组(维度 1)。所以如果我想得到这个名字,我必须做$user[0]['first_name']
.
I tried using limit(1)
or take(1)
, or even using ->toArray()
but there was no difference.
我尝试使用limit(1)
or take(1)
,甚至使用->toArray()
但没有区别。
What am I doing wrong?
我究竟做错了什么?
回答by Ganesh Jogam
Simply use this:
只需使用这个:
$user = User::whereEmail($email)->first();
回答by Koushik Das
You can do this too
你也可以这样做
Before you use this you must declare the DB facade in the controller Simply put this line for that
在你使用它之前,你必须在控制器中声明 DB 门面 简单地把这一行
use Illuminate\Support\Facades\DB;
Now you can get a row using this
现在你可以使用这个获得一行
$getUserByEmail = DB::table('users')->where('email', $email)->first();
or by this too
或者通过这个
$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);
This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.
这个返回一个数组,其中只有一个项目,而第一个返回一个对象。记在脑子里。
Hope this helps.
希望这可以帮助。
回答by Haritsinh Gohil
Using Laravel Eloquent you can get one row using first()
method,
使用 Laravel Eloquent,您可以使用first()
方法获得一行,
it returns first row of table if where()
condition is not found otherwise it gives the first matched row of given criteria.
如果where()
没有找到条件,它返回表的第一行,否则它给出给定条件的第一个匹配行。
Syntax:
句法:
Model::where('fieldname',$value)->first();
Example:
例子:
$user = User::where('email',$email)->first();
//OR
//$user = User::whereEmail($email)->first();
回答by Hussam Adil
laravel 5.8
拉拉维尔 5.8
If you don't even need an entire row, you may extract a single value from a record using the value()
method. This method will return the value of the column directly:
如果您甚至不需要整行,您可以使用该value()
方法从记录中提取单个值。此方法将直接返回列的值:
$first_name = DB::table('users')->where('email' ,'me@mail,com')->value('first_name');
check docs
检查文档
回答by antelove
Laravel 5.2
Laravel 5.2
$sql = "SELECT * FROM users WHERE email = $email";
$user = collect(\User::select($sql))->first();
or
或者
$user = User::table('users')->where('email', $email)->pluck();
回答by Gagandeep
You can also use this
你也可以用这个
$user = User::whereEmail($email)->first();