2
votes

I am in development of a personal project.

I have two models 'Show' and 'Episode'. I have one controller 'Ops'.

Show model:

class Show extends AppModel
{
 var $name = 'Show';

 var $hasMany = array(
  'Episode' => array(
   'className' => 'Episode',
   'foreignKey' => 'show_id'
  )
 );
}

Episode model:

class Episode extends AppModel
{
 var $name = 'Episode';

 var $belongsTo = array(
  'Show' => array(
   'className' => 'Show',
   'foreignKey' => 'show_id'
  )
 ); 
}

Ops controller:

class OpsController extends AppController
{
 var $name = 'Ops';
 var $uses = array('Show','Episode');

 function index()
 {
  $episodes = $this->Episode->find('all',array(
   'limit' => 10,
   'order' => array('Episode.first_aired' => 'DESC'),
   )
  );
  debug($this->Episode);
  debug($episodes);

 }
}

When running the Ops controller I get the 'Episode' records like I want but don't get the associated 'Show' record based on the 'show_id' in the 'belongsTo' configuration. It appears that it is not referencing the model at all as I can purposefully break the model class an the request still goes on.

After doing a lot of checking, researching, and testing, I was able to get it to work by adding the following into the Ops controller before the find() request:

$this->Episode = ClassRegistry::init('Episode');
$this->Episode->bindModel(
 array('belongsTo' => array(
   'Show' => array(
    'className' => 'Show'
   )
  )
 )
);

Now while this works I would still like to know why my models are not being called properly. Any help would be most appreciated. Thanks!

3

3 Answers

0
votes

What happens if you query Show in the same way?

Are you certain the id fields are defined correctly?

On both tables you should have id(INTsize) and on episodes there should also be show_id(INTsize).

If it's set up according to Cake convention, you should be able to remove the 'foreignKey' => 'show_id' line and Cake will sort it out itself.`

0
votes

It sounds like Cake isn't using your model files and instead automagically generating some based on the tables. It sounds dumb, but check the folders and file names for spelling errors and that they are lowercase.

0
votes

In your Show model, you have the Episode foreign key set to show_id, which should be episode_id. However, I don't think that is causing the problem.

You aren't changing any CakePHP naming conventions, from what I can tell, so just remove the arrays that define the association and leave as string, e.g.

class Show extends AppModel
{
 var $name = 'Show';

 var $hasMany = array(
  'Episode'
 );
}

class Episode extends AppModel
{
 var $name = 'Episode';

 var $belongsTo = array(
  'Show'
 ); 
}

This may not work, but I have bumped into similar issues before and this resolved it. Good luck.