Query database within model

Is there a way to query the database for instances of a model within that model itself? For example:




class MyModel extends CActiveRecord

{

  public function usefulFunction()

  {

    // I want to do this

    $usefulObject = MyModel::model()->findByPk(3);


    if ($usefulObject->boolean_attribute)

    {

      // cool stuff here

    }

  }


}



I have tried parent::findByPk(3), $this->findByPk(3), etc, but to no avail, what’s the proper way of doing this?

Have U tried self::model()->finByPk();

1 Like

I discovered my error. I wasn’t actually passing the literal ‘3’ into the function, but rather $object->integer_attribute. My $object wasn’t defined properly.

Thanks for the input dragon, the self keyword makes sense in referencing to the whole class as opposed a single instance the way the ‘this’ keyword would.

As a side note, it seems MyModel()::model()->usefulFunction() is equivalent to self::model()->usefulFunction(), though self may be better.

Is there a reason why you are doing this and not just instantiating your model somewhere and then having your function work on itself?