如何获取 phalcon 中具有最大列值的记录?

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

我正在尝试获取具有最大 faq_order 列的 row/record。

场景:我有一个tablefaq_category,它包含一个字段faq_orderFAQ_ORDER列负责存放订单号。

faq_category 中创建新记录时,我想设置 faq_order 但它应该具有最新值。即假设是否有 2 个以前的记录,以便记录将分别具有 faq_order 值 1、2!现在在第三条新记录上它应该将 faq_order 设置为 3 但我尝试了下面的代码但没有找到正确的方法。

保存功能:

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' );
}

型号:

/**
 * 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();
}

您应该使用 ORM 聚合函数:https://docs.phalconphp.com/3.2/en/db-models#generating-calculations

这是一种方法:

function beforeValidationOnCreate()
{
    $this->faq_order = \YourModelClassame::maximum([
        'column' => 'faq_order'
    ]) + 1;
}

这样,当您从此 table 创建记录时,它将始终具有最高的 faq_order 值 :)