模特没有加入

时间:2014-06-26 22:33:55

标签: php mysql cakephp cakephp-2.0 cakephp-model

我有4张桌子:

  • 向导(id,name)
  • 页面(id,page_number,wizard_id)
  • modules(id,name)
  • modules_pages(id,page_id,module_id,wizard_id)

模型是默认设置。

向导有一个页面,一个页面有一个模块。 modules_pages是一个联结表。当我从向导或页面显示数组时,我无法获得模块列表,这些数据由页面的当前wizard_id或我传递的页面过滤。它只是多次显示模块。


页面模型

    public $belongsTo = array(
    'Wizard' => array(
        'className' => 'Wizard',
        'foreignKey' => 'wizard_id',
    ),
);
public $hasAndBelongsToMany = array(
    'Module' => array(
        'className' => 'Module',
        'joinTable' => 'modules_pages',
        'foreignKey' => 'page_id',
        'associationForeignKey' => 'module_id',
        'unique' => 'keepExisting',
    )
);

模块模型

public $hasAndBelongsToMany = array(
    'Page' => array(
        'className' => 'Page',
        'joinTable' => 'modules_pages',
        'foreignKey' => 'module_id',
        'associationForeignKey' => 'page_id',
        'unique' => 'keepExisting',
    ),
);

public $hasOne = array(
    'CodeReference' => array(
        'className' => 'CodeReference',
        'foreignKey' => 'code_reference_id',
    ),
);

向导模型

    public $hasMany = array(
    'Page' => array(
        'className' => 'Page',
        'foreignKey' => 'wizard_id',
        'dependent' => false,
        'conditions' => 'ModulesPage.wizard_id = Wizard.id',
    )
);

控制器

$this->loadModel('Page');
    $this->Page->recursive = 1;
    $options = array('Page.wizard_id' => $wizard_id);
    $page = $this->Page->find('first', $options);
    $this->set('page');

    $this->loadModel('ModulesPage');
    $this->ModulesPage->recursive = 2;
    $options = array('ModulesPage.wizard_id ' => $wizard_id,
                     'ModulesPage.page_number' => $page_number,
                     'ModulesPage.enabled' => 1);
    $modules = $this->ModulesPage->find('all', $options);

1 个答案:

答案 0 :(得分:0)

首先在AppModel中设置以下内容:     public $ recursive = -1;

您将该代码放入哪个控制器?你不应该使用loadModel - 因为你已经在模型文件中加入了模型,你可以像这样访问。

// access Module model from within PagesController
$this->Page->Module->find('all', $options);

您的$ options设置中也存在错误。条件以数组形式提供,但它们需要位于另一个名为“条件”的数组中,例如

$options = array(
    'conditions' => array(
        //conditions go here
    )
);

最后,在关闭递归后,您需要启用可包含的行为。更改上面给出的$ options数组,如下所示(此示例将获取所有Pages及其向导和模块)

$options = array(
    'conditions' => array(
        //conditions go here
    ),
    'contain' => array(
        'Wizard',
        'Module'
    )
);
$data = $this->Page->find('all', $options);

您可以使用其他数组键进一步定义查询的其他选项,例如: '订购',' group','限制'等

相关问题