How can i get the first record with laravel 4 raw queries.
Something like DB::select('')->first();
is not working neither did DB::first('')
欢迎各位兄弟 发布技术文章
这里的技术是共享的
I have a row query \DB::select("SELECT * FROM table_name WHERE id=$id");
the result should get only one array as the first result
this is what i get
But i need like this
DB::select() and DB::get() will give an array or a collection (in the latest Laravel)
You can call ->first() to get the first item.
you must be using Laravel 5.2 or earlier.
You can do this.
collect(\DB::select("SELECT * FROM table_name WHERE id=$id"))->first();
Why not use Query Builder and do something like this:
$user = DB::table('users')->where('id', $id)->get();
If you need to get specific columns:
$user = DB::table('users')->where('id', $id)->pluck('id', 'name');
nasik21 said:
->first() gives error Call to a member function first() on array
You should call ->first() "in place" of ->get() or select() , not after. I need to hint though, that ->first() returns the row as an object (rather than array)
来自 https://laravel.io/forum/09-23-2016-db-select-get-only-first-row
6 | |||||||||||||
|
18 | The fact is that DB:select() returns an array, so you have to:
You also can
| ||||||||||||
|
1 | Like this:
| ||||
|
0 |
| ||
0 | When using eloquent you can do this:
| ||