CakePHP HABTM添加/编辑问题

时间:2014-04-10 01:35:08

标签: cakephp cakephp-2.4

我有以下关系:

版:

    public $hasAndBelongsToMany = array(
    'Band' => array(
        'className' => 'Band',
        'joinTable' => 'bands_editions',
        'foreignKey' => 'edition_id',
        'associationForeignKey' => 'band_id',
        'unique' => true,
    )
);

频段:

    public $hasAndBelongsToMany = array(
    'Edition' => array(
        'className' => 'Edition',
        'joinTable' => 'bands_editions',
        'foreignKey' => 'band_id',
        'associationForeignKey' => 'edition_id',
        'unique' => true,
    )
);

BandsController:

public function add()
{
    if($this->request->is('post'))
    {
        $this->Band->create();
        if($this->Band->save($this->request->data))
            doSomething();
        else
            doSomethingElse();
    }
}

public function edit($id = NULL)
{
    $this->Band->id = $id;
    if(!$this->Band->exists())
        throw new NotFoundException(__('Not found'));

    if($this->request->is('post') || $this->request->is('put'))
    {
        if($this->Band->save($this->request->data))
            doSomething();
        else
            doSomethingElse();
    } else {
        $this->request->data = $this->Band->read(NULL, $id);
    }
}

当我尝试使用add()填充Bands时,一切顺利,但只要我调用edit(),Cake就会停止并显示以下错误: 致命错误:在非对象上调用成员函数schema()

调试时,我发现当解析器到达有关请求类型的检查时会触发错误。

我的错误是什么?

1 个答案:

答案 0 :(得分:0)

试试这个,我没看到它是否有效

public function edit($id = null){
    if(!$id){
        throw new NotFoundException(__("Invalid Post"));
    }

    $band = $this->Band->findById($id);

    if (!$band) {
        throw new NotFoundException(__('Invalid Post'));
    }

    if ($this->request->is(array('post', 'put'))) {
        $this->Band->id = $id;
        if ($this->Band->save($this->request->data)) {
            doSomething();
        }
        else {
            doDomething();
        }
    }

    if (!$this->request->data) {
        $this->request->data = $Band;
    }
}