【问题标题】:CakePHP not respecting foreignKey nameCakePHP 不尊重 foreignKey 名称
【发布时间】:2017-11-14 17:28:07
【问题描述】:

我有一个 articles 表,其中有一列 tagging_id 需要引用名为 tracking_categories 的表中的 id 列作为外键。

我的Article.php 文件包含以下内容:

class Article extends AppModel {
    public $controllerPath = 'articles';
    public $useTable = 'articles';

var $binds = array(
    'TrackingCategory' => array(
        'bindType' => 'belongsTo',
        'className' => 'TrackingCategory',
        'foreignKey' => 'tagging_id'
    ),
    'Channel' => array(
        'bindType' => 'belongsTo',
        'className' => 'Channel',
        'foreignKey' => 'channel_id'
    )
);

我的TrackingCategory.php 看起来像这样:

class TrackingCategory extends AppModel {

     public $useTable = 'tracking_categories';

我在Article.php 继承的AppModel 中有以下内容:

function expects($binds, $reset = false) {
    if (func_num_args() > 2 || !is_bool($reset)) {
        throw new InvalidArgumentException('Did you mean to pass an 
array of binds?');
    }

    if (!is_array($binds)) {
        $binds = array($binds);
    }

    foreach ($binds as $bind) {

        if (isset($this->binds[$bind])) {
            $tmp = array($this->binds[$bind]['bindType'] => array($bind => $this->binds[$bind]));
            $this->bindModel($tmp, $reset);
        }
    }
}

我收到以下错误: Database Error Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Article.tracking_category_id' in 'field list'

它仍在寻找通过 CakePHP 的命名约定解析的列,而不是我通过 foreignKey 值明确设置的名称。我在这里错过了什么?

【问题讨论】:

    标签: mysql cakephp foreign-keys cakephp-2.0


    【解决方案1】:

    正确的语法应该是:

    public $belongsTo = array(
        'TrackingCategory' => array(
            'className' => 'TrackingCategory',
            'foreignKey' => 'tagging_id',
        )
    );
    

    有关详细信息,请参阅CakePHP 2.x - Associations: Linking Models Together - belongsTo

    【讨论】:

    • 替代语法适用于该模型中的所有其他绑定,但不适用于这个新的。这是组织的现有项目。我不能只是去改变工作语法。
    • 感谢您的回复。我编辑了问题以包含绑定且正常工作的 Channel。唯一的区别是 channel_id 确实符合 CakePHP 的命名约定。
    • 检查其他工作模型在代码中某处是否有类似$this->bindModel($this->binds); 的内容。它可以从构造函数或beforeFind() 回调中调用。
    • 是的,我们有这个,这当然就是这种替代语法的工作方式,但这对 Cake 忽略我的外键名称应该没有任何影响,对吧?
    • 好的,已编辑。我在Article.php 中没有该功能,但Article.php 扩展了AppModel,它就在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多