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