Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I think I have a quiet simple error but i can't solve it... I try to associate two tables:

  • projects hasMany keywords
  • keywords belogsTo projects

My code:

<?php
class KeywordsController extends AppController{
    public function add(){
        $projects = $this->Keyword->Project->find('list'); //***here is the error***
        //pr($projects);

        if ($this->request->is('post')) {
            $this->Keyword->save($this->request->data);
            $this->redirect('/keywords');   
        }
    }
}

<?php
class ProjectsController extends AppController{
    public function add(){
        if ($this->request->is('post')) {
            $this->Project->save($this->request->data);
            $this->redirect('/projects');   
        }
    }
}

<?php
class Project extends AppModel{
    public $hasMany = 'Keyword';
}

<?php
class Keyword extends AppModel{
    public $belongsTo = 'Project';

}

Error message:

Error: Call to a member function find() on a non-object
File: /Users/me/Localhost/cakephp/app/Controller/KeywordsController.php
Line: 7

like image 211
CTSchmidt Avatar asked Oct 28 '25 17:10

CTSchmidt


1 Answers

Add below line above the class declaration for models.

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

also define name property for class definition.

public $name = 'Project';
public $name = 'Keyword';

For Project Model

<?php
App::uses('AppModel', 'Model');
class Project extends AppModel{
    public $name = 'Project';
    public $hasMany = 'Keyword';
}

For Keyword Model

<?php
App::uses('AppModel', 'Model');
class Keyword extends AppModel{
    public $name = 'Keyword';
    public $belongsTo = 'Project';

}

Edit

$this->loadModel('Project');
$projects = $this->Project->find('list');
like image 124
Dipesh Parmar Avatar answered Oct 31 '25 08:10

Dipesh Parmar