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

时间:2019-02-06 14:26:01

标签: php sorting phalcon phalcon-orm

我正在尝试获取具有最大faq_order列的行/记录。

场景:我有一个表faq_category,其中包含字段faq_order FAQ_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();
}

1 个答案:

答案 0 :(得分:1)

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

这是一种实现方式:

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

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