代码之家  ›  专栏  ›  技术社区  ›  Dan Passaro Andry

CakePHP-HABTM:编辑一个项目会导致HABTM行被重新创建,并破坏额外的数据

  •  1
  • Dan Passaro Andry  · 技术社区  · 14 年前

    我在CakePHP的HABTM关系有问题。

    我有两个这样的模型: Department HABTM Location . 一家大公司有许多大楼,每栋大楼提供的服务数量有限。每个建筑也有自己的网页,因此除了HABTM关系本身之外,每个HABTM行也有一个 url

    我将模型设置为:

    <?php
    class Location extends AppModel {
        var $name = 'Location';
    
        var $hasAndBelongsToMany = array(
            'Department' => array(
                'with' => 'DepartmentsLocation',
                'unique' => true
            )
        );
    }
    ?>
    
    
    <?php
    class Department extends AppModel {
        var $name = 'Department';
    
        var $hasAndBelongsToMany = array(
            'Location' => array(
                'with' => 'DepartmentsLocation',
                'unique' => true
            )
        );
    }
    ?>
    
    <?php
    class DepartmentsLocation extends AppModel {
        var $name = 'DepartmentsLocation';
    
        var $belongsTo = array(
            'Department',
            'Location'
        );    
    
    
        // I'm pretty sure this method is unrelated. It's not being called when this error
        // occurs. Its purpose is to prevent having two HABTM rows with the same location
        // and department.
        function beforeSave() {
    
            // kill any existing rows with same associations
            $this->log(__FILE__ . ": killing existing HABTM rows", LOG_DEBUG);
    
            $result = $this->find('all', array("conditions" =>
                array("location_id" => $this->data['DepartmentsLocation']['location_id'],
                      "department_id" => $this->data['DepartmentsLocation']['department_id'])));
    
    
            foreach($result as $row) { 
                $this->delete($row['DepartmentsLocation']['id']);
            }
    
            return true;
        }
    }
    ?>
    

    控制器完全没有意思。

    问题是: 如果我编辑一个 位置 ,所有 DepartmentsLocation 位置

    我想知道两件事:

    还有,用一种不那么专业、更爱发牢骚的语气:为什么会发生这种情况?在我看来很奇怪,通过Cake编辑字段会带来这么多麻烦,当我可以轻松地通过phpMyAdmin时,编辑 位置 说出你的名字,就能得到我所期望的结果。当我只是编辑一行上的字段时,为什么CakePHP会接触HABTM数据?它甚至不是外键!

    3 回复  |  直到 14 年前
        1
  •  1
  •   harpax    14 年前

    根据食谱,第一个问题是:

    默认情况下,在保存 有一种亲密的关系,蛋糕 将删除联接表上的所有行

    我不太清楚为什么Cake会尝试保存HABTM数据,即使您的数据中没有外键,但有一个简单的解决方案。简单地 destroy the association 对于保存呼叫:

    $this->Location->unbindModel(
        array('hasAndBelongsToMany' => array('Department'))
    );
    
        2
  •  1
  •   pawelmysior    14 年前

    我在想这可能发生的一个原因。当你找回 Location ,您还可以检索 locations_departments 数据。当你做一个 save($this->data) 它在阵列中查找模型并保存它们。

    recursive (模型的)属性 -1 0 var $recursive = -1; 或在控制器方法(操作)中: $this->ModelName->recursive = -1;

    有关递归的详细信息: http://book.cakephp.org/view/439/recursive

    这真的很像什么 哈尔巴

        3
  •  0
  •   Guillaume Esquevin    14 年前

    麻烦的是,在拯救你的生命时 Location DepartmentsLocations 也因此,CakePHP破坏一切,并试图重新创建它。

    这是蛋糕的一个常见错误,因为它会给你带来太多的结果。