【问题标题】:CakePHP ordered behavior with multiple foreign keysCakePHP 具有多个外键的有序行为
【发布时间】:2011-12-02 20:09:32
【问题描述】:

据我所知,CakePHP 没有用于处理记录重新排序的内置机制。因此,我正在使用Ordered Behavior,据我所知,这是在 CakePHP 中重新排序的事实行为。到目前为止,当我将它添加到各种模型中时,它运行良好,但是,我遇到了一种我不知道如何处理的情况。

我的模型层次结构如下。

Section > Heading > Category > Item

但是,项目可以直接附加到部分:

Section > Item

Item 模型的表同时定义了 category_idsection_id,但实际上只有一个用于任何给定记录。

当您设置模型的$actsAs 时,有序行为设置了两个参数。这是我的标题模型:

var $actsAs = array('Ordered' => array('field' => 'order','foreign_key' => 'section_id'));

我应该如何为具有两个外键 section_idcategory_id 的 Item 模型定义 $actsAs 成员,以确保正确维护排序/序列?

【问题讨论】:

  • 要获得答案,您可能需要添加一个示例,说明您提供的输入和您希望的输出。我不太明白您要创建什么效果。
  • 我不确定您所说的输入是什么意思。我所拥有的是一个模型,它可以是两个模型之一的子模型,并且有序行为基于外键维护给定模型组的排序,因此附加到类别 X 的项目的排序独立于附加到类别 Y 的项目、A 节和 B 节。这有助于澄清吗?
  • 这需要进行大量更改。我建议为“部分项目”设置“不可见”类别。
  • @AlexanderMorland 感谢您的推荐并感谢您将这段代码贡献给社区。无需重新处理我现有的所有数据层次结构,我找到了一个似乎可行的解决方案。如果您在其中看到任何您认为可能有问题的内容,请告诉我,但到目前为止,它似乎正在做我需要的事情。

标签: cakephp behavior


【解决方案1】:

我没有对此进行过广泛的测试,但在我第一次尝试时,这似乎是一种解决方法,可以让我动态管理排序。在我的ItemsController 中,我有以下操作:

    function moveup($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Item', true));
        } else {
            $item = $this->Item->read(null, $id);

            if ($item['Item']['section_id'] != 0) {
                $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'section_id'));
            } else {
                $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'category_id'));
            }

            if ($this->Item->moveup($id)) {
                $this->Session->setFlash(__('Item moved up', true));
            } else {
                $this->Session->setFlash(__('Item move failed', true));
            }
        }

        $this->redirect($this->referer());
    }

    function movedown($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Item', true));
        } else {
            $item = $this->Item->read(null, $id);

            if ($item['Item']['section_id'] != 0) {
                $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'section_id'));
            } else {
                $this->Item->Behaviors->attach('Ordered', array('field' => 'order', 'foreign_key'=>'category_id'));
            }

            if ($this->Item->movedown($id)) {
                $this->Session->setFlash(__('Item moved down', true));
            } else {
                $this->Session->setFlash(__('Item move failed', true));
            }
        }

        $this->redirect($this->referer());
    }

我的模型没有通过$actsAs 成员设置有序行为(因此也没有设置foreign_key)。相反,在任何订单操作之前,我会确定父项类型并附加行为,并在运行时使用适当的foreign_key

【讨论】:

  • 我想我看到的最大问题是它违反了 MVC 模式,将模型逻辑放入控制器中。有人对如何将其构建到模型中提出建议吗?
猜你喜欢
  • 2015-08-24
  • 2010-09-29
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
相关资源
最近更新 更多