1

I have the MySQL query for the result I need:

SELECT `delivery_date` FROM `order_grids` ORDER BY str_to_date(`delivery_date`, "%b %d, %Y") DESC

As we have custom ORDER BY so I am facing issue to implement it in CakePHP 2.x.

Generally, in case of normal field sorting we do as below. I have a VARCHAR type field delivery_date which stores date in format Jan 21, 2015 and need sorting on that column.

I already have the MySQL query as shown above:

$this->Paginator->sort('delivery_date','Delivery Date');

Please assist.

3
  • You can use a virtual field. However, storing dates in a VARCHAR is not a good idea. Feb 5, 2016 at 14:51
  • @InigoFlores - actually this is an ongoing project so we cannot change the field type. Can you please explain how i can use my sql query so it works in cake php way.
    – Afroz Alam
    Feb 5, 2016 at 19:05
  • I understand. See if my answer helps. Feb 5, 2016 at 22:35

1 Answer 1

2

You can accomplish this by creating a virtual field.

Since virtual fields behave much like regular fields when doing find’s, Controller::paginate() will be able to sort by virtual fields too.

Add the following to your OrderGrid model:

public function __construct($id = false, $table = null, $ds = null) {
    parent::__construct($id, $table, $ds);
    $this->virtualFields['delivery_date_proper'] = sprintf('STR_TO_DATE(%s.delivery_date, "%%b %%d, %%Y") ', $this->alias);
}

This will allow you to sort by delivery_date_proper when paginating.

See

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.