0

I have an array as collection and ordered it in ascending order with respect to expiry date as below:

$creditDetails = $this->_creditFactory->create()
                      ->addFieldToFilter('customer_id', 1)
                      ->setOrder('date_expires', 'asc');

I have some records which do not have any expiry date i.e NULL

I want such records to come in collection at the end of or after the records which have some expiry date. Now, records without expiry date are executing first.

How can I do this ?

1 Answer 1

1

Im not sure about magento. However, in MySQL null values are ranked lower than actual values, so naturally they would appear at the top of an ascending list. However there is a way around this in MySQL.

using a minus sign before the column name, instructs MySQL to push NULL values to a higher ranking (above the thing with the minus sign).

Note: the minus sign operator works really well for integers and dates, but there are other methods you can use for alphanumeric columns.

that said you could try the following.

$creditDetails = $this->_creditFactory->create()->addFieldToFilter('customer_id', 1)->setOrder('-date_expires', 'asc');

notice the - before 'date_expires'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.