[英]How to fetch a record having max column value in phalcon?
I am trying to fetch a row/record having max faq_order
column.我正在尝试获取具有最大
faq_order
列的行/记录。
Scenario : I have a table faq_category
and it contains a field faq_order
.场景:我有一个表
faq_category
并且它包含一个字段faq_order
。 FAQ_ORDER column is responsible for storing the order number. FAQ_ORDER列负责存储订单号。
While creating new record in faq_category
I want to set faq_order
but it should be having latest value.在
faq_category
创建新记录时,我想设置faq_order
但它应该具有最新值。 ie let say if there is 2 previous records so that records will be having faq_order values 1, 2 respectively!即假设是否有 2 个以前的记录,以便记录将分别具有 faq_order 值 1、2! 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.
现在在第三条新记录上它应该将faq_order设置为 3 但我尝试了下面的代码但没有找到合适的方法。
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();
}
You should be using ORM aggregation functions: https://docs.phalconphp.com/3.2/en/db-models#generating-calculations您应该使用 ORM 聚合函数: https : //docs.phalconphp.com/3.2/en/db-models#generating-calculations
Here is one way of doing it:这是一种方法:
function beforeValidationOnCreate()
{
$this->faq_order = \YourModelClassame::maximum([
'column' => 'faq_order'
]) + 1;
}
This way when you are creating record from this table it will always have the highest faq_order
value :)这样,当您从此表创建记录时,它将始终具有最高的
faq_order
值:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.