【问题标题】:CakePHP 2.x HABTM returning is no matching resultsCakePHP 2.x HABTM 返回的是没有匹配的结果
【发布时间】:2014-02-26 22:44:52
【问题描述】:

我在使用 cakephp 的 habtm 时遇到问题,我还不知道如何解决。我有三个表:setores、veiculos 和 setores_veiculos。

Setor 模型:

public $hasAndBelongsToMany = array(
    'Veiculo' => array(
        'className' => 'Veiculo',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'setor_id',
        'associationForeignKey' => 'veiculo_id',
        'unique' => 'keepExisting'
    )
);

Veiculo 模型:

public $hasAndBelongsToMany = array(
    'Setor' => array(
        'className' => 'Setor',
        'joinTable' => 'setores_veiculos',
        'foreignKey' => 'veiculo_id',
        'associationForeignKey' => 'setor_id',
        'unique' => 'keepExisting'
    )
);

在我的 setores 控制器中,我有:

$options = array('conditions' => array('Setor.' . $this->Setor->primaryKey => $id));    
$setores = $this->Setor->find('first', $options);

然后在我的调试中:

array(
'Setor' => array(
    'id' => (int) 5,
    'nome' => '2º Batalhão',
    'secretaria_id' => (int) 6,
    'sigla' => '2º BPM',
    'status_id' => (int) 1
),
'Veiculo' => array()
)

我不明白为什么没有列出 Veiculo(车辆)。插入工作正常。

我预计:

 'Veiculo' => array(
     0 => array(
        'id' => 1,
        'name' => 'Corolla'
     ),
     1 => array(
          'id' => 2,
        'name' => 'Hillux'
    )
  );

在我的 veiculos 控制器中列出了 setores。有什么建议吗?

提前谢谢你,对不起我的英语。

【问题讨论】:

    标签: php cakephp-2.0 has-and-belongs-to-many


    【解决方案1】:

    我觉得不错。尝试改变

    'unique' => 'keepExisting'
    

    'unique' => true
    

    目前,我遵循文档中解释的简单规则,如果我使用简单的链接表,即不存储任何数据,我使用 HABTMunique设置为 true,否则我使用 hasMany through (The Join Model)unique set to keepExisting 以免丢失额外存储的数据。

    发布 setores_veiculos 的数据转储。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多