11

I know I can use another model inside a controller by doing $this->loadModel("MyModel"), but how do I do this inside another Model? I tried to use loadModel but it didn't work.

Any idea?

Thank you

hakre
  • 193,403
  • 52
  • 435
  • 836
user765368
  • 19,590
  • 27
  • 96
  • 167
  • Possible duplicate of [Can I use one model inside of a different model in CakePHP?](https://stackoverflow.com/questions/980556/can-i-use-one-model-inside-of-a-different-model-in-cakephp) – icc97 Jul 06 '17 at 12:54

3 Answers3

27

Easier is:

$my_model = ClassRegistry::init('MyModel');

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

Community
  • 1
  • 1
Costa
  • 4,851
  • 33
  • 30
  • 1
    This is the best way. If you use `App::import` or `App::uses` with model constructor then will be problem e.g. with TranslateBehavior. Reason: `DboSource` class use `ClassRegistry::getObject` to get model and read virtual fields. So to prevent using two instances of the same model use this solution. – dmajka Apr 28 '21 at 09:55
4

You can use the following code to export a model that is not associated with the current model in any way:

App::import('Model', 'MyModel');
$my_model = new MyModel();

If MyModel is associated with current model you could use the chaining e.g. $this->SomeModel->MyModel

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
Ehtesham
  • 2,967
  • 1
  • 18
  • 20
0

You don't need to import anything. Just do this:

$my_model = new MyModel();
//Then
$my_model->read(null,$id);
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92