1

Suppose I have Model1 and it is not associated to Model2 by hasOne or any other relation. How can I access info from Model2?

I tried the following way:

Model/Model1.php

class Model1 extends AppModel{

public function getInfo(){

  App::uses('Model2','Model');

  $mod2_info=$this->Model2->find('all');
  return $mod2_info;

 }
}//end of class

Controllers/Model1sController.php

class Model1sController extends AppController{

public function index(){

 set('info', $this->Model1->find('all'));

 }
}//end of class

View/Model1/index.ctp

   <?php var_dump($info);   ?>

Browser Output:
Fatal error:Call to a member function find() on a non-object in Model/Model1.php

tereško
  • 58,060
  • 25
  • 98
  • 150
DaGambit
  • 55
  • 1
  • 8

3 Answers3

1

Well there is the bindModel method, which allows you to create ad-hoc associations.

Of course, using bindModel there still have to be valid foreign keys in the model's database table. Alternatively you could use loadModel in Model1sController:

$this->loadModel('Model2');

The find method of Model2 then becomes available. loadModel is strictly a controller method though, so you can't use it in a model and probably isn't what you're looking for.

Lastly, inside Model1 you could get a Model2 instance and use its find method by doing the following:

$Model2 = ClassRegistry::init('Model2');
$Model2->find('all');
mensch
  • 4,411
  • 3
  • 28
  • 49
1

There's two ways to handle this, you can use the $uses array if every method in your Controller needs to use the model. Use this when a controller necessarily depends on these models.

In this example the ProductionController uses these three Models in all it's methods, so they're incuded in $uses as a necessary part of the controller.

 var $uses = array('DailyProdn', 'ProdnMode', 'Prod');

Note this adds some overhead, so only use $uses if this Model is a * necessary part of the controller*. Otherwise, load the Model ad hoc. You can use $this->loadModel() to load in a Model inside a method in an ad hoc style.

Here the ProductionController is loading the Plant model. Put this inside a Method before you try to access the Plant Model for find() ect. This is great when you need to ad hoc use a Model in just a few Methods.

 $this->loadModel('Plant');
Ben Brocka
  • 2,006
  • 4
  • 34
  • 53
0

on top of your first model write this:

App::uses('MyModel', 'Model');

But then you will need to call it differently:

$my_model = new MyModel();
$my_model->anyOtherMethod();
$my_model->read(null, '1');

More info from here

Community
  • 1
  • 1
Fury
  • 4,643
  • 5
  • 50
  • 80