【问题标题】:Cakephp HABTM association is not workingCakephp HABTM 协会不起作用
【发布时间】:2014-06-24 16:31:37
【问题描述】:

我需要一个治疗师有很多孩子的协会,反之亦然。

我有 3 张桌子:

治疗师 孩子们 儿童治疗师

你可以在下面看到关联:

治疗师.php

 public $hasAndBelongsToMany = array('Child' =>
                array(
                               'className' => 'Children',
                               'joinTable' => 'children_therapists',
                               'foreignKey' => 'therapist_id',
                               'associationForeignKey' => 'child_id',
                               'unique' => true,
                               'conditions' => '',
                               'fields' => '',
                               'order' => 'Child.last_name',
                               'limit' => '',
                               'offset' => '',
                               'finderQuery' => '',
                               'with' => ''
                           )
    );

在 Child.php 模型中,我尝试了以下代码:

public $useTable = 'children';

但这没有用。

当我对它进行编码时,我收到以下错误:

缺少数据库表

错误:在数据源默认值中找不到模型 Child 的子表。

非常感谢任何帮助。

谢谢, 格雷格

【问题讨论】:

  • 问题出在 Children 模型,而不是 Child 模型。 Cake 正在寻找儿童桌(通常称为childrens)。您需要在 Children 模型中设置 $useTable = 'children';
  • 或者,如果 Children 实际上不是模型,则需要将关联中的 className => Children 更改为 Child。

标签: php cakephp


【解决方案1】:

不使用子模型

因为问题中的代码没有引用它。

public $hasAndBelongsToMany = array(
    'Child' => array(
       'className' => 'Children',
//                    ^ Supposed to be a model name

它引用了不存在的Children 模型。

突出显示数组键和类名键的含义:

class User extends AppModel {

    public $hasAndBelongsToMany = array(
        'Friend' => array(
    //  ^ Whatever you want
           'className' => 'Child',
    //                    ^ A model name

一个简单的修复

要更正所提出的问题,只需替换

'className' => 'Children'

'className' => 'Child'

【讨论】:

  • 感谢您的帮助。当我将 className 更改为“Child”时,出现此错误:致命错误错误:调用非对象文件上的成员函数 schema():/var/www/lib/Cake/Model/Model.php 行:第3575章
  • 那么比问题中的错误更多 =) - 查看the line of code in your app 并确定它试图访问的内容(即$assoc 是什么)以及为什么它不是模型对象.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多