【问题标题】:Association finding wrong table关联查找错误的表
【发布时间】:2014-09-20 07:49:17
【问题描述】:

我正在尝试为我的 DomainTypes view() 函数包含我的 DomainTypes 表的子项,但它抱怨“错误:SQLSTATE[42S22]:找不到列:1054 Unknown column 'Children.domain_type_id' in 'where子句'" 问题是我的 DomainTypes 表没有 domain_type_id 列。域表可以。这是我的 DomainTypes view() 的代码:

public function view($id) {
    if (!$id) {
        throw new NotFoundException(__('Invalid DomainType'));
    }

    $domainType = $this->DomainTypes
        ->find()
        ->where(['DomainTypes.id' => $id])
        ->contain(['Parent', 'Children', 'Affiliates'])
        ->first();

    $this->set(compact('domainType'));
}

关于我的设置。我有 2 个表,域和域类型。两者都使用树行为。

这是域表的初始化代码:

public function initialize(array $config){
    parent::initialize($config);

    $this->displayField('name');
    $this->addBehavior('Tree');

    //Associations
    $this->hasMany('Children', [
        'className' => 'Domains',
    ]);
    $this->belongsTo('Parent', [
        'className' => 'Domains',
    ]);
    $this->belongsTo('Affiliates');
    $this->belongsTo('DomainTypes');
}

这是域类型表的初始化代码:

public function initialize(array $config){
    parent::initialize($config);

    $this->displayField('name');
    $this->addBehavior('Tree');

    //Associations
    $this->hasMany('Children', [
        'className' => 'DomainTypes',
    ]);
    $this->belongsTo('Parent', [
        'className' => 'DomainTypes',
    ]);
    $this->belongsTo('Affiliates');
    $this->hasMany('Domains');
}

两者非常相似,但也明确定义了要使用的 className。为什么 Cakephp 3 假设我的 DomainTypes 表上有一个 domain_type_id 列?提前致谢!

【问题讨论】:

    标签: cakephp tree cakephp-3.0


    【解决方案1】:

    我们都很亲近,但并不完全正确。 ndm,您的回答很有帮助,因为它确实指出了我犯的另一个错误。最终的关联代码应如下所示:

        $this->hasMany('Children', [
            'className' => 'DomainTypes',
            'foreignKey' => 'parent_id',
        ]);
        $this->belongsTo('Parent', [
            'className' => 'DomainTypes',
        ]);
    

    当我尝试输入外键时,我使用的不是“foreignKey”,而是几乎没用的“foreign_key”。感谢ndm的帮助。

    【讨论】:

      【解决方案2】:

      更新我没有好好注意,CakePHP 在自动生成一个名为 domain_type_id 的外键时似乎实际上是正确的,它是一个 hasMany 关联,所以 FK 应该基于源表。

      解决方案仍然相同,需要明确设置 FK,正如 @MjGaiser 已经指出的那样,belongsTo 关联的 parent_id 不是必需的,而是 hasMany 关联的 FK应该使用parent_id 而不是child_id

          $this->hasMany('Children', [
              'className' => 'DomainTypes',
              'foreignKey' => 'parent_id'
          ]);
          $this->belongsTo('Parent', [
              'className' => 'DomainTypes'
          ]);
      

      【讨论】:

      • 如果我只使用belongsTo 关系,那将是有意义的,但不应该有“child_id”,因为hasMany 应该使用孩子的parent_id。如果您同时拥有 parent_id 和 child_id,您将复制数据并使您的网站面临更多问题。还是我不明白你要去哪里?
      • @MjGaiser 不,你说得对,我只是没注意,应该没有child_id,而CakePHP 生成一个名为domain_type_id 的FK 实际上似乎是正确的。我会更新我的答案并删除废话:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多