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");
Related
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
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 a project using Symfony 2 and containing Doctrine 2 entities. Some of these entities are related to each other. This association is defined by an annotation:
/**
* #ORM\OneToMany(targetEntity="Event", mappedBy="firstEntityId" cascade={"persist", "remove"})
* #ORM\OrderBy({"dateEnd" = "DESC", "dateBegin" = "DESC"})
*/
private $events;
As you can see, this association contains several events that have a start and an end date. When retrieving this collection, I want to have the most recents events (i.e. those which have not ended yet or have ended recently) sorted first.
The problem with the current approach is that it will sort events with an end date of NULL after all other events.
How can I tell Doctrine to sort the events with an end date of NULL first and then sort the remaining events by descending end date?
I have so far seen several questions on SO about how to tell Doctrine how to order entities. However, none of them mention annotations. Tricks with reversing the sign as suggested e.g. in Doctrine 2 Order By ASC and Null values in last do not work because Doctrine does not accept anything other than a property name and ASC or DESC in the annotation.
It's an old post but i found a pretty simple solution if you are using doctrine query builder :
$sortDirection = 'ASC';
$qb = $this->createQueryBuilder('e');
$qb->addSelect('CASE WHEN e.valueToOrder IS NULL THEN 1 ELSE 0 END AS HIDDEN myValueIsNull');
//other stuffs
//$qb->where ...
$qb->orderBy('myValueIsNull','ASC');
$qb->addOrderBy('e.valueToOrder',':sortDirection');
$qb->setParameter(':sortDirection',$sortDirection);
return $qb->getQuery()->getResult();
PHP way, besides being slower, avoid to use offsets (for an infinite scroll for example)
Thanks to https://stackoverflow.com/a/23420682/6376420
Probably not. There is an SQL syntax that allows to ORDER BY column DESC NULLS FIRST. However, it is not supported by all DB vendors and thus if I scanned the merge request correctly, has not been merged into DQL. Depending on which database platform you use, you may be lucky. The comments in the merge request provide insight into how to extend Doctrine at different points to implement the behavior, maybe that helps you to do it by yourself.
My workaround is to create add an additional select to the query and extract the entity from the resulting array collection, it would be better to have it only examined in query time and not select it (to keep the result array intact) but I have not found a proper solution to this yet (using QueryBuilder).
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('e')
->from(Entity::class, 'e')
// We use ZZZZ here as placeholder to push the null values last, use 'AAAA' to sort them first.
->addSelect('CASE WHEN(e.name IS NULL) THEN \'ZZZZ\' ELSE e.name END AS name')
->addOrderBy('name', 'ASC');
// As we have a array result due to the "addSelect()" above, we must extract the entities now, in this example by looping over the result array.
$entities = array_map(function ($contributor) {
return $contributor[0];
}, $queryBuilder->getQuery()->getResult());
I had the same problem and this was my approach:
If we are not talking about a huge amount of processing you can use a custom sort, I needed to have the results sorted by a column in asc or desc depending on user choice. BUT, I also needed the null values of the same column to appear first. So after a lot of googling for the NULLS FIRST approach I decided to make an usort right after you get the result from the query builder:
// Custom sort to put the nulls first
usort($invoices, function(Entity $a, Entity $b) use ($order) {
if(null === $a->getNumber())
return -1;
if(null === $b->getNumber())
return 1;
if(strtoupper($order) == "DESC") {
if($a->getNumber() > $b->getNumber())
return -1;
if($b->getNumber() > $a->getNumber())
return 1;
} else {
if($a->getNumber() < $b->getNumber())
return -1;
if($b->getNumber() < $a->getNumber())
return 1;
}
});
This way when you get the results from the QueryBuilder you will get the NULLS first and then you will have your original sorting. if it was ASC it will stay ASC and vice-versa.
In case NULL values are required at the end you just need to change the first 'if' to the contrary sign.
I know this question is already Answered but thought I might leave this here in case it helps someone else.
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]).