CakePHP Fatal Error Calling a member function () on a non-object

I have some problems finding a solution for this.

Error: Call to a member function schema() on a non-object File: /Cake/Model/Model.php Line: 3627 

My database has article tables, hashtags, and the association of articles_hashtags with foreignkeys article_id and hashtag_id .. Therefore, I try to get the information that each article hashtags has.

Model of my article

 class Article extends AppModel { public $hasAndBelongsToMany = array( 'Hashtag' => array( 'className' => 'Hashtag', 'joinTable' => 'articles_hashtags', 'foreignKey' => 'article_id', 'associationForeignKey' => 'hashtag_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'with' => '' ) ); } 

Article controller

 class ArticleController extends AppController { var $name = 'Article'; public $helpers = array("Html", "Form"); public function index() { $this->set("posts", $this->Article->find("all")); } } 

Thanks for the help!

Optional: If I put the generated sql select query from the sql debugger log into my sql database, I get the correct results. So I think something is wrong with the controller ?!

+7
php cakephp many-to-many has-and-belongs-to-many model-associations
source share
3 answers

I had the same problem as truncated $hasAndBelongsToMany to the minimum keys.

The problem is that you are using the "c" key in the $hasAndBelongsToMany . Remove this or set it to 'articles_hashtags':

 class Article extends AppModel { public $hasAndBelongsToMany = array( 'Hashtag' => array( 'className' => 'Hashtag', 'joinTable' => 'articles_hashtags', 'foreignKey' => 'article_id', 'associationForeignKey' => 'hashtag_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'with' => 'articles_hashtags' ) ); } 

The library model code tried to access the key value "c", which was empty, therefore, a non-object error.

From the CakePHP docs related to the $hasAndBelongsToMany :

  • with Defines the model name for the connection table. By default, CakePHP will automatically create a model for you. Using the example above, it will be called IngredientsRecipe. Using this key, you can override this default name. The connection table model can be used as any "normal" model for direct access to the connection table. By creating a model class with this name and file name, you can add any user-defined behavior to the lookup table, for example, add additional information / columns to it.
+17
source share

Have you initialized the model object in your controller? You can do this using the $ uses field in the controller. Add the following line to ArticleController:

 public $uses = array('Article'); 
0
source share

Multiple controller names

You do not need to declare an article model in ArticlesController, cake magic does this for you.

0
source share

All Articles