Can I use one model inside of a different model in CakePHP?

Solution 1:

Old thread but I'm going to chime in because I believe the answers to be incomplete and lacking in "why". CakePHP has three ways to load models. Though only two methods work outside of a Controller, I'll mention all three. I'm not sure about version availability but this is core stuff so I believe they'll work.

App::import() only finds and require()s the file and you'll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.

ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up "Cake" things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I've found useful.

Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that's your situation, I'd use this method before the others.

Solution 2:

You can create instances of other models from within any model/controller using one of these two methods.

If you're using Cake 1.2:

App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);

If you're using Cake 1.1:

loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);

Solution 3:

An obvious solution everyone missed is to create an association between two models, if appropriate. You can use it to be able to reference one model from inside another.

class Creation extends AppModel {
    public $belongsTo = array(
        'Inventor' => array(
            'className'  => 'Inventor',
            'foreignKey'  => 'inventor_id',
        )
    );

    public function whoIsMyMaker() {
        $this->Inventor->id = $this->field('inventor_id');
        return $this->Inventor->field('name');
    }
}

Solution 4:

In CakePHP 1.2, it's better to use:

ClassRegistry::init('Attribute')->save($data);