Use Model inside another Model without association in cakephp

Just imagine a situation where you have

  • 1 Parent model (ModelA) and 1 Child model ModelB
  • You don’t have any model association from parent model to child model like hasOne or hasMany
  • But you want to Write query for ModelA and the result will featch data from child Model “ModelB”
  • And you you want this without any association

So Question is how to do this, here is the solution

Goto Parent Model i.e ModelA

In the top of the page just write 1 line. Just after starting php TAG & just before the keyword “class”, add following like.

So just add this like to ModelA.php page.

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

Now you will be able to write Query for ModelB from the ModelA itself. Consider following mode function

Public function  getChildNode(){

  $ModelB = new ModelB();           
  $resultArr = $ModelB->find('all');
  retrun $resultArr;
}

 

So this way you can write cross model Query. Just for your reference i am giving you entire ModelA.php Codes.

<?php

App::uses('ModelB', 'Model');
Class ModelA extends AppModel{
  Public function  getChildNode(){ 
    $ModelB = new ModelB();            
    $resultArr = $ModelB-&gt;find('all');  retrun $resultArr;}
}

Keep Coding 😛