Search code examples
cakephpassociationsaliascakephp-bake

Cakephp Error: Call to a member function find() on a non-object


I have the following model:

class Adjustment extends AppModel {
   var $name = 'Adjustment';       
    var $belongsTo = array(
    'Source_Budget'=>array('className'=>'Budget','foreignKey'=>'s_budget_id'),
    'Target_Budget'=>array('className'=>'Budget','foreignKey'=>'t_budget_id'),
    'Source_Project'=>array('className'=>'Project','foreignKey'=>'s_project_id'),
    'Target_Project'=>array('className'=>'Project','foreignKey'=>'t_project_id')

  );

model budget and project are as below

class Budget extends AppModel {
var $name='Budget';
var $belongsTo = array('Year');
var $hasMany=array('Project','Payment','Revenue',
'AdjustmentFrom'=>array('className'=>'Adjustment','foreignKey'=>'s_budget_id'),
'AdjustmentTo'=>array('className'=>'Adjustment','foreignKey'=>'t_budget_id'),
'TransferFrom'=>array('className'=>'Transfer','foreignKey'=>'s_budget_id'),
'TransferTo'=>array('className'=>'Transfer','foreignKey'=>'t_budget_id')
 );

class Project extends AppModel {
   var $name = 'Project';
   var $belongsTo = array('Budget','Year');

    var $hasMany=array('Payment','Revenue',
'AdjustmentFrom'=>array('className'=>'Adjustment','foreignKey'=>'s_project_id'),
'AdjustmentTo'=>array('className'=>'Adjustment','foreignKey'=>'t_project_id'),
'TransferFrom'=>array('className'=>'Transfer','foreignKey'=>'s_project_id'),
'TransferTo'=>array('className'=>'Transfer','foreignKey'=>'t_project_id')
  );

I have succesfully created a controller with scaffolding which adds/deletes/updates adjustments but when I bake the code I get the message "Error: Call to a member function find() on a non-object " when I try to add an adjustment.

The error is on the following line:

$sourceBudgets = $this->Adjustment->SourceBudget->find('list');
$targetBudgets = $this->Adjustment->TargetBudget->find('list');
$sourceProjects = $this->Adjustment->SourceProject->find('list');
$targetProjects = $this->Adjustment->TargetProject->find('list');
$this->set(compact('sBudgets', 'tBudgets', 'sProjects', 'tProjects'));

Off cource there is no model SBudget, TBudget, SProject, TProject so I edited the code as below:

   $sourceBudgets = $this->Adjustment->Budget->find('list');
   $targetBudgets = $this->Adjustment->Budget->find('list');
   $sourceProjects = $this->Adjustment->Project->find('list');
   $targetProjects = $this->Adjustment->Project->find('list');
   $this->set(compact('sBudgets', 'tBudgets', 'sProjects', 'tProjects'));

and I added the line public $uses = array('Budget', 'Project');

in the Adjustment controller class. Unfortunatly the problem persists and I always get the "Error: Call to a member function find() on a non-object" message.


Solution

  • The aliases you have used in the belongsTo association in first block of code are wrong. Instead of Source_Budget it should be SourceBudget. Similarly for other aliases drop the underscore.