CodeIgniter Forums

Full Version: The wonders of order_by
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I just discovered this and it is wonderful. I hope it is not dangerous/wrong or ill advised. Thought I would mention it and perhaps suggest the documentation should mention it, as it is very handy to know.

I had an online shop where I wanted to order the sale items by the amount saved, i.e. product price minus sale price. I was struggling for a while on how to do this when I had an idea to try this - and it worked perfectly.

Code:
$this->db->order_by('product_price - product_sale_price', 'DESC');

The wonders of codeigniter, one line did it all.

I was about to change the admin adding of sale price to add in a column on the product table for saving amount, which would have been a pain.

I am personally very happy with this! Thank you CI for being so perfect!  Smile

Best wishes,

Paul.
That's really more having to do with SQL than CI though.

ORDER BY field1 - field2

is perfectly valid SQL
True of course, just didn't realise I could put whatever was valid SQL into order_by, very glad I could though and relieved when it worked so well. I just think I wanted to mention it. Looking forward to trying out some date comparisons and sorting in it too.

Best wishes,

Paul.
Be careful with dynamic ORDER BY conditions ... you may put a lot of overhead on the database that way.
(09-01-2015, 02:50 AM)Narf Wrote: [ -> ]Be careful with dynamic ORDER BY conditions ... you may put a lot of overhead on the database that way.

Thanks for the warning. Much appreciated and duly noted.

Best wishes,

Paul.