Is There A 'first' And 'last' Method In Ar Like In Rails?


(Zeratool23) #1

Hello,

I’m new here and i’d like to ask if there a ‘first’ and ‘last’ method in AR like in Rails?

THanks!


(Kburton) #2

There’s no direct equivalent. What are you looking to use them for?

In the case of first(), just doing a find based method (rather than findAll based) will return only the first matching result, or null if no results were found. There’s no inbuilt way to replicate the last() method.


(Yii) #3

You can use CActiveRecord::find and pass a CDbCriteria with condition and order.


(Stephane Belanger174) #4

select max(id) id being the pk




$model = new Model;

$criteria=new CDbCriteria;

$criteria->select='max(column) AS maxColumn';

$row = $model->model()->find($criteria);

$somevariable = $row['maxColumn'];




(Zeratool23) #5

"What are you looking to use them for?"

Since the result is an array, in rails if you use .first will return the $arr[0] element while .last will return $arr[$arr.length - 1]