We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to fetch a record having max column value in phalcon?

I am trying to fetch a row/record having max faq_order column.

Scenario: I have a table faq_category and it contains a field faq_order. FAQ_ORDER column is responsible for storing the order number.

While creating new record in faq_category I want to set faq_order but it should be having latest value. i.e let say if there is 2 previous records so that records will be having faq_order values 1, 2 respectively! Now on third new record it should set the faq_order to 3 but I tried the below code but didn't found a proper way.

Save function:

public function saveGeneralFaqCategoryAction(){

    // Instantiate new form for EbFaqCategoryModel
    $form = new EbFaqCategoryForm();

    if( $form ->isValid($this->request->getPost())){

        // Get the FAQ Category id (if any)
        $id = $this->request->get( 'id', null );

        // Get existing FAQ Category (if any) or create a new one
        if( null !== $id && $id !== '' ) {

            $faqCategory = EbFaqCategoryModel::findFirst( $id );

        } else {
             // Here we create new instance and I'm stuck here!
            // Logic in my mind is get max order and +1 it and then save it 
            // in new instance
            $faqCategory = new EbFaqCategoryModel();
            //$maxOrder = EbFaqCategoryModel::get(); 
            $faqCategory->setFaqOrder(); // On new I want to set max value

        }
        // Bind form with post data
        $form->bind( $this->request->getPost(), $faqCategory );
        $faqCategory->save();
    } else {
        // Send error Json response
        return CxHelper::SendJsonError($form->getHtmlFormattedErrors());
    }

    // Return success
    return array( 'data' => 'Success' );
}

Model:

/**
 * Get Current Max Order
 *
 * @return array
*/
public static function getCurrentMaxOrder(){
    $queryBuilder = new Builder();

    return  $queryBuilder
        ->from(array('c' =>  static::class))
        ->columns('c.*')
        ->where('c.faq_order', MAX) // HERE I want to get a Record having faq_order max
        ->orderBy("c.date_created desc")
        ->getQuery()
        ->execute()->setHydrateMode(Resultset::HYDRATE_ARRAYS)
        ->toArray();
}


8.4k
Accepted
answer
edited Mar '19

this should return the maximum value

EbFaqCategoryModel::maximum(array("column" => "faq_order"));

PHQL

SELECT MAX(EbFaqCategoryModel.faq_order) AS maximum FROM EbFaqCategoryModel