php - CakePHP 对非对象成员函数 schema() 的 fatal error 调用

标签 php cakephp many-to-many model-associations has-and-belongs-to-many

我在为此找到解决方案时遇到了一些麻烦..

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

在我的数据库中有表 articleshashtags 和关联 articles_hashtags 与外键 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' => ''
               )  
            ); 
          }

文章 Controller

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

    } 
}

感谢您的帮助!

另外: 如果我将调试器 sql 日志中生成的 sql select 查询放入我的 sql 数据库,我会得到正确的结果。所以我猜 Controller 有问题?!

最佳答案

我遇到了同样的问题,所以将 $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'
        )  
      ); 
   }

库模型代码试图访问“with”键的值,该键为空,因此出现非对象错误。

From CakePHP docs ,关于 $hasAndBelongsToMany 数组:

  • with: Defines the name of the model for the join table. By default CakePHP will auto-create a model for you. Using the example above it would be called IngredientsRecipe. By using this key you can override this default name. The join table model can be used just like any “regular” model to access the join table directly. By creating a model class with such name and filename, you can add any custom behavior to the join table searches, such as adding more information/columns to it.

关于php - CakePHP 对非对象成员函数 schema() 的 fatal error 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25797796/

相关文章:

php - where 子句在 cakephp 3.4 中不起作用

java - 延迟初始化@ManyToMany。错误是什么?

android - 在 Realm for Android 中从子访问父

PHP 两个表更新

php - 如何使用 PHP 管理服务器运行时的 secret ?

php - 是否可以将消息推送到使用应用程序 ID 注册的所有设备?

symfony - 多对多和奏鸣曲管理捆绑

php - 如何在运行 PHPUnit 的骨架测试之前设置全局变量

cakephp - webtechnick Facebook 注销不起作用

php - Cakephp 3 的虚拟字段