Yii Framework Forum: Retrieving Results Using Ar Find And Findall - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Retrieving Results Using Ar Find And Findall Rate Topic: -----

#1 User is offline   Larry Z. 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 17
  • Joined: 11-February 13

Posted 28 February 2013 - 07:54 PM

Hi, to determine if any records are returned using find() and findAll(), I see that when nothing is returned using find(), that a NULL is returned. When nothing is found using findAll, that an empty array is returned.

Is this the best way to determine if records are returned?:

$var=SomeModelClass::model()->find($condition, $params);

if ($var !== null) 
    // Check if a single record is returned.



$var=SomeModelClass::model()->findAll($condition, $params);

if (!empty($var))
   // Check for returned records



Thanks for any advice.

Larry Z.
0

#2 User is offline   Keith 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,584
  • Joined: 04-March 10
  • Location:UK

Posted 01 March 2013 - 07:16 AM

For arrays, I tend to use count(), although you can get away with just using the array as a boolean expression - it will be treated as false if it is empty and true otherwise. If you want consistency, you can therefore do this:

$var=SomeModelClass::model()->find($condition, $params);

if ($var) 
    // Check if a single record is returned.


$var=SomeModelClass::model()->findAll($condition, $params);

if ($var)
   // Check for returned records


If you want to make the code slightly more readable, you could do this:

$var=SomeModelClass::model()->find($condition, $params);

if ($var !== null) 
    // Check if a single record is returned.


$var=SomeModelClass::model()->findAll($condition, $params);

if (count($var))
   // Check for returned records


As an aside, I tend to code these sorts of checks using more of a guard pattern. Actual example from the top of an action:

    public function actionEdit($userId)
    {
        $user = User::model()->findByPk($userId);

        if (!$user)
            throw new CHttpException(404, 'User not found.');

        ...

    }

0

#3 User is offline   Larry Z. 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 17
  • Joined: 11-February 13

Posted 02 March 2013 - 12:10 AM

Actually if (!empty($var) works in both cases, so I'm just using that.

Thanks Keith

Larry Z
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users