CakePHP致命错误调用非对象上的成员函数schema()

tob*_*sas 7 php many-to-many cakephp has-and-belongs-to-many model-associations

我找到一个解决方案有点麻烦..

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

在我的数据库中有表格文章,主题标签和关联articles_hashtags与foreignkeys article_id和hashtag_id ..所以我想知道每篇文章有哪些主题标签..

我的文章模型

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' => ''
               )  
            ); 
          }
Run Code Online (Sandbox Code Playgroud)

文章管理员

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

    } 
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!!

另外:如果我将生成的sql select查询从调试器sql日志放入我的sql数据库中,我得到了正确的结果..所以我猜控制器出了问题?!

小智 18

我遇到了同样的问题,因此可能会删除$hasAndBelongsToMany最小的键.

问题是你在$hasAndBelongsToMany数组上使用'with'键.删除它或将其设置为'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'
        )  
      ); 
   }
Run Code Online (Sandbox Code Playgroud)

库模型代码试图访问'with'键的值,该键为空,因此是非对象错误.

从CakePHP文档,关于$hasAndBelongsToMany数组:

  • with:定义连接表的模型名称.默认情况下,CakePHP将为您自动创建模型.使用上面的例子,它将被称为IngredientsRecipe.通过使用此键,您可以覆盖此默认名称.连接表模型可以像任何"常规"模型一样直接访问连接表.通过创建具有此类名称和文件名的模型类,您可以向连接表搜索添加任何自定义行为,例如向其添加更多信息/列.