CakePHP不尊重foreignKey名称

时间:2017-11-14 17:28:08

标签: mysql cakephp foreign-keys cakephp-2.0

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

我的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';

AppModel Article.php继承了以下内容:

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值明确设置的名称。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

正确的语法应该是:

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

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