Russell Sk. Russell Sk. -4 years ago 248
PHP Question

Yii2 check if ActiveRecord Successfully loaded a record

How to check if data exists in DB and loaded in the ActiveRecord model. For example, in Kohana, there is function

to check that ORM successfully loaded a record.

class Model_Image extends ORM {
public function url($width = NULL)
if( ! $this->loaded()){
return NULL;

I have got the class named Image it is extended from ActiveRecord. Class Image has url function, inside function url I should check if a data was loaded, or it is the new one?

Is there something similar in Yii2 to check if ActiveRecord successfully loaded a record.

Answer Source

When you use findOne() (simply one()) on ActiveRecord model where condition is not met it returns null.

When you use findAll() (simply all()) on ActiveRecord model where condition is not met it returns empty array.

So all you need to check is if the ActiveRecord is not empty.


$model = MyActiveRecordModel::findOne(1);
if (empty($model)) {
    // DB row not found
} else {
    // DB row found

Additionally you can check boolean property isNewRecord of model:

if ($model->isNewRecord) {
    // no previously db data loaded - 
    // new instance of model (new data not saved yet)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download