I have the following query. I want to get data from the database sorted alphabetically:
$states = State::where('status', 1)->sortBy('name')->get();
Which framework are you using
If laravel then write below syntax
$states = State::where('status', 1)->orderBy('name', 'ASC')->get();
You need to use order by SQL keywords to get it alphabetically ordered data as ascending or descending order. For laravel use check Ordering, Grouping, Limit, & Offset from laravel docs.
For your use case it is simple as
$states = State::where('status', 1)->orderBy('name', 'ASC')->get();
for ascending order
Related
Im using laravel 5.2 and I want to group a table based on the value of two columns (configuration and type). So basically if two or more rows in the table have the same configuration and type they will be grouped.
I've tried querying like this and its not working:
$groups = Model::where('active', 1)->get()->groupBy('type_id', 'configuration_id');
Any suggestions?
EDIT: I think I'm using the wrong query. What I want to do is get the rows that have the same values in these two columns and have them grouped. Apparently group by is used to aggregate things e.g if I want a sum or something.
EDIT 2: Actually the groupby here I'm using is not part of the query it is a helper function provided by laravel to use on collections see this link Does anyone know if it groups by two feilds??
Ok I've figured it out.
The groupBy method I'm using is not a query it is a laravel function that groups collections by a certain field. You can see the documentation here. So the workaround was to do the grouping twice like this.
$groups = Model::where('active', 1)->get()->groupBy('type_id');
foreach ($groups as $group) {
$grouped[] = $group->groupBy('configuration_id');
}
Pass Columns names in array form this is working for me
$groups = Model::where('active', 1)->groupBy(['type_id', 'configuration_id','etc']);
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get();
Try like this
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id');
$groups = Model::where('active', 1)->groupBy('type_id', 'configuration_id')->get(['type_id', 'configuration_id']);
I want to show timestamp descending order, but my query is not working, here is my code:
$this->db->order_by("DATE(field_name)", "DESC");
I am getting this, but when I display in jquery datatable, it became ascending order, how to solve this?
In jQuery Datatable, you have an config option to sort the table, by default, the first one. Be sure it is well positionned if you want to keep a specific data order.
$('#myDataTable').DataTable({
order: [[0, 'desc']],
});
The first argument 0 is index of the column to sort by (here, the first column, 1 for the second one, etc).
Or, you can disable Datatable sorting, passing an empty array to the order option :
$('#myDataTable').DataTable({
order: [],
});
You need to remove DATE in your query.
Please try below
$this->db->order_by("field_name", "DESC");
Here filed_name = Your table field value (timestamp in this case.)
Also, if it does not work please provide your error.
The problem here is Jquery Datatable, which by default order by the first column of the table.
If ordering is enabled (ordering), then DataTables will perform a first pass order during initialisation. Using this parameter you can define which column(s) the order is performed upon, and the ordering direction. The order must be an array of arrays, each inner array comprised of two elements:
see more on Datatables Order
you have two options here, all of them in the JS code,dont worry about the php code.
order in datatables:
like this:
$("#table").dataTable({
"order":[[positionofcolumtoorder,'desc']]
});
Remove the order function from Datatables during the initial load
as this:
$('#table').dataTable( {
"order": []
} );
Try this code :
$this->db->order_by("field_name", "DESC");
$this->db->order_by("field_name", "DESC");
I have a database containing a large amount of information that a user can query using PHP to communicate with the MySQL database. I also want to limit their results to be at most 300 results, which I have successfully done. However, I also want to sort the results by dataset name. Is there a way to sort the end query, not the original table? From what I've read online, the ORDER BY statement in a query sorts the whole table and then does the query (or something similar) Sorting the query would be more efficient, as you would only be sorting say 15 records instead of 1500000. If it helps at all, I print the results to the page using the following syntax:
while ($row = mysql_fetch_array($result)) {
...
}
Thanks
If the result set is limited, save it into a php array then use the php sorting functions: http://php.net/manual/en/function.usort.php
$all = array();
while ($res = mysql_fetch_array($result)) {
$all[] = $res;
}
usort($all, function($a,$b) {
return $a['field'] < $b['field'];
});
Just make sure what you are sorting by has a decent index and the sort option should be very fast. The issue with sorting before/after a LIMIT is that if it were possible (which it is with a bit of GROUP BY logic), it would change the actual results you get as opposed to just the order they return in.
To create a sub table and only sort on that you could attempt something like:
Select * from ( QUERY limit 300) a order by COLUMN
I have 3 columns id, msg and created_at in my Model table. created_at is a timestamp and id is primary key.
I also have 5 datas, world => time4, hello => time2,haha => time1,hihio => time5 and dunno => time3 and these datas are arranged in ascending order (as arranged here) based on their id.
In laravel 4, I want to fetch these data, arrange them in ascending order and take the last n(in this case, 3) number of records. So, I want to get dunno,world and hihio rows displayed like this in a div :
dunno,time3
world,time4
hihio,time5
What I have tried
Model::orderBy('created_at','asc')->take(3);
undesired result :
haha,time1
hello,time2
dunno,time3
Also tried
Model::orderBy('created_at','desc')->take(3);
undesired result :
hihio,time5
world,time4
dunno,time3
I have also tried the reverse with no luck
Model::take(3)->orderBy('created_at','asc');
This problem seems fairly simple but I just can't seem to get my logic right. I'm still fairly new in Laravel 4 so I would give bonus points to better solutions than using orderBy() and take() if there is. Thank you very much!
You are very close.
It sounds like you want to first order the array by descending order
Model::orderBy('created_at','desc')->take(3);
but then reverse the array. You can do this one of two ways, either the traditional PHP (using array_reverse).
$_dates = Model::orderBy('created_at','desc')->take(3);
$dates = array_reverse($_dates);
Or the laravel way, using the reverse function in Laravel's Collection class.
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
Check out Laravel's Collection documentation at their API site at http://laravel.com/api/class-Illuminate.Support.Collection.html
Now $dates will contain the output you desire.
dunno,time3
world,time4
hihio,time5
You're pretty close with your second attempt. After retrieving the rows from the database, you just need to reverse the array. Assuming you have an instance of Illuminate\Support\Collection, you just need to the following:
$expectedResult = $collection->reverse();
To get last three rows in ascending order:
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
Now, the json output of $_dates will give you a object of objects.
To get array of objects use:
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse()->values();
$reverse = Model::orderBy('created_at','desc')->take(3);
$show = $reverse->reverse();
I need to order data by two columns (when the rows have different values for column number 1, order by it; otherwise, order by column number 2)
I'm using a QueryBuilder to create the query.
If I call the orderBy method a second time, it replaces any previously specified orderings.
I can pass two columns as the first parameter:
->orderBy('r.firstColumn, r.secondColumn', 'DESC');
But I cannot pass two ordering directions for the second parameter, so when I execute this query the first column is ordered in an ascending direction and the second one, descending. I would like to use descending for both of them.
Is there a way to do this using QueryBuilder? Do I need to use DQL?
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.
For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.
To add multiple order by's you need to use 'add' function. And it will be like this.
->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.
More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api
Hope this helps. Cheers!
you can use ->addOrderBy($sort, $order)
Add:Doctrine Querybuilder btw. often uses "special" modifications of the normal methods, see select-addSelect, where-andWhere-orWhere, groupBy-addgroupBy...
You can use orderBy() followed by an addOrderBy() - nesting several orderBy()'s is not possible, but nesting several addOrderBy()'s also works after the initial orderBy().
Example:
$this->createQueryBuilder('entity')
->orderBy('entity.addDate', 'DESC')
->addOrderBy('entity.id', 'DESC')
The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:
# Inside a Repository method:
$myResults = $this->createQueryBuilder('a')
->addOrderBy('a.column1', 'ASC')
->addOrderBy('a.column2', 'ASC')
->addOrderBy('a.column3', 'DESC')
;
# Or, using a OrderBy object:
$orderBy = new OrderBy('a.column1', 'ASC');
$orderBy->add('a.column2', 'ASC');
$orderBy->add('a.column3', 'DESC');
$myResults = $this->createQueryBuilder('a')
->orderBy($orderBy)
;
The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).