• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The wonders of order_by

#1
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.
Reply

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

ORDER BY field1 - field2

is perfectly valid SQL
Reply

#3
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.
Reply

#4
Be careful with dynamic ORDER BY conditions ... you may put a lot of overhead on the database that way.
Reply

#5
(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.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.