orderBy field name in laravel query - laravel

I want to order the query value based on status order 8,1,2,3,4,5,6,7.I have the query.Is is possible to sort by given value. I want to order the query result in the given order 8,1,2,3,4,5,6,7
$query->orderBy('status','DESC') //order by 8,1,2,3,4,5,6,7
->get();

you can use orderByRaw() method

Related

Efficient way to query database with multiple conditions in laravel

Is it possible to make this a single query?
$yl_min = DB::connection($this->db2)->table('historical')
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->min('low_usd');
$yl = DB::connection($this->db2)->table('historical')
->select('id','coin','low_usd','created_time','created_at')
->where([['slug','=',$crypto_id],['low_usd',$yl_min]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->first();
I've tried this but no luck:
$yl = DB::connection($this->db2)->table('historical')
->select('id','coin','created_time','created_at',DB::raw('SELECT MIN(low_usd) as low_usd'))
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->first();
After looking at your query code, I found the two query condition is same, and you just want to get min low_usd record,
I think you can just use the multiple condition and ORDER BY low_usd ASC, then take the first one:
$yl = DB::connection($this->db2)->table('historical')
->where([['slug','=',$crypto_id],['low_usd','!=', null]])
->whereBetween('created_time',[$this->range_1y,$this->hislatest])
->orderBy('low_usd','asc')
->select('id','coin','low_usd','created_time','created_at')
->first();
After this, if you want to make this query more efficient,
you need to add index on slug, low_usd, created_time

Eloquent query to get Highest and 2nd highest value in database

I have a problem with Laravel Eloquent to get the subject name with the highest value and second highest value from the 'student_number' where the subject group = 'E1'.
This is what I have tried but it contains an error "max(): When only one parameter is given, it must be an array" and I don't know how to get the 2nd highest value of 'student_number'.
public function electiveGroup(){
$E1 = FinalyearSubject::get()
->where('subject_group','=','E1')
->orWhere('student_number','=',max('student_number'));
return view ('admin.elective')->with(compact('E1'));
}
FinalyearSubject::where('subject_group', 'E1')
->orderBy('student_number', 'DESC')
->limit(2)
->get()
Explanation:
Add filters
Order them by student_number descending
Take the top 2
get() the result
In your example, the moment you are doing FinalyearSubject::get(), the query is already done. get() returns a Collection object (more like an enriched array). Everything you chain afterwards is calculated using Laravel's Collection utilities. ->get() usually should be the last thing in your call so that you can do as much work in SQL as possible.
So, Question is you want maximum of all and 2nd maximum of subject
group = 'E1'.
Max of all
FinalyearSubject::where('subject_group','E1')
->max('student_number');
2nd max of 'E1'
FinalyearSubject::where('subject_group','E1')
->OrderBy('student_number','desc')
->offset(1)
->limit(1)
->get();

How Can I Understand Eloquent orderBy() Works?

Please help me understand how orderBy works. Look at the following code.
$posts = Post::orderBy('title','asc')->get();
When I use orderBy('title','asc') does it mean I receive all of the Post records and put them into
$posts and then order them by title ascending? I'm confused with orderBy(). I remember
when we want to receive all the records we should type "all" after Post so how does orderBy() do that?
Exactly, orderBy method allows you to sort the result of the query by a given column.
If using orderBy your query should look like:
$posts = Post::orderBy('title','asc')->get();
When using all() you query would be:
$posts = Post::all();
Yes, it's exactly what you said.
The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:
$users = DB::table('users')
->orderBy('name', 'desc')
->get();
Take a look at the docs to see more info about this

Laravel query builder - Select elements unique or null on specific column

I have a model Form for table forms. There is a column called guid which can be null, or contain some sort of grouping random hash.
I need to select all forms that have column guid either null or unique in current search. In other words, for repeating guid values in current search I select only first occurence of every guid hash.
I tried:
$results = App\Form::where(... some where clauses .. ).groupBy('guid')
and it's almost ok, but for all rows, where guid == NULL it groups them and selects only one (and I need all of them).
How can I get the unique or null rows either by building proper SQL query or filtering the results in PHP?
Note: I need my $results to be an Illuminate\Database\Eloquent\Builder instance
EDIT:
I fount out that SQL version of query I need is:
SELECT * FROM `forms` WHERE .... GROUP BY IFNULL(guid, id)
What would be equivallent query for Laravel's database query builder?
UPDATE: Using DB::raw
App\Form::where(... conditions ...)
->groupBy(DB::raw("IFNULL('guid', 'id')"));
Or the another way could be:
You can also use whereNotNull, whereNull & at last merge both the collections using merge() like this:
First get the results where guid is grouped by (excluding null guid's here):
$unique_guid_without_null = App\Form::whereNotNull('guid')->groupBy('guid')->get();
Now, get the results where guid is null:
$all_guid_with_null = App\Form::whereNull('guid')->get();
and at last merge both the collections using merge() method:
$filtered_collection = $unique_guid_without_null->merge($all_guid_with_null);
Hope this helps!
For your edited question, you can use raw() as;
->groupBy(DB::raw("IFNULL('guid', 'id')"))
So your final query will be as:
$results = App\Form::where(... some where clauses .. )
->groupBy(DB::raw("IFNULL('guid', 'id')"));
By above query, your $results will be an instance of Illuminate\Database\Eloquent\Builder.

Eloquent ORM select all with limit and column name

Hi how can I select limited number of all the item from model and the selection with certain names.
eg:
$product = Product::all()->limit(4)->select('id','name');
Most of example start with Product::find(1) but my case, I don't have id. Thanks
Use the other methods first, then call get at the end:
$products = Product::limit(4)->select('id', 'name')->get();
Limit Query Results
To limit the number of results returned from the query, or to skip a given number of results in the query, you may use the skip() and take() methods:
Example of User model which extends Eloquent:
$users = User::take(5)->skip(10)->get();
Product::all() will be used when get all data without any condition. You need to use get method.
you need to
$products = Product::select('id', 'name')->limit(4)->get();

Resources