【问题标题】:How do I add multiple related records programmatically in a HABTM CakePHP relationship scenario?如何在 HABTM CakePHP 关系场景中以编程方式添加多个相关记录?
【发布时间】:2012-08-25 04:07:51
【问题描述】:

我已经设置好模型,以便用户属于组。这两者之间存在有效的 HABTM 关系。

下面的代码用于用一些演示数据填充数据库。在下面的 sn-p 之前,Groups 表中已经填充了一些示例组数据。

下面的代码 sn-p 有效。它将记录添加到用户表中,并且连接表 (groups_users) 也获得了正确的条目。所以基本上,HABTM 关系很好。

这是我的问题:如何添加与 多个 组的关联,而不仅仅是单个关系?做一个

'Group'=>array($group1, $group2)
而不是下面概述的
'Group'=>$group1'
不起作用。当我使用数组时,连接表中根本没有添加任何内容。

非常感谢您的帮助!

$groups = $this->Group->find('all');
  for ($i=0; $i<=200; $i++) {                   
$groupIndex1 = rand(0, count($groups)-1);
$groupIndex2 = rand(0, count($groups)-1);

$this->User->set(
  array(
    'id'=>null,
    'name'=>'Dummy User '.$i0,
    'Group'=>$groups[$groupIndex1]
  )
);
$this->User->save();

【问题讨论】:

  • 请提供您的两个模型中指定的关系代码。

标签: cakephp cakephp-2.0 cakephp-model


【解决方案1】:

要为单个用户保存多个组,您必须在用户模型中定义hasMany 关系。在您的保存代码中,它看起来像:

$groups = $this->Group->find('all');
for ($i=0; $i<=200; $i++) {                   
$groupIndex1 = rand(0, count($groups)-1);
$groupIndex2 = rand(0, count($groups)-1);
$data  = 
  array('User' => array(
                        'id'=>null, 
                        'name'=>'Dummy User '.$i0,
                       ),
        'Group'=> array($groups[$groupIndex1], $groups[$groupIndex2])
  )
);
$this->User->saveAssociated($data, array('deep' => true);

This link 可能会帮助您理解'deep' =&gt; true 选项。

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多