1

このコードが機能しない理由がわかりません。はbeforeSave呼び出されていません。保存に失敗し、デバッグログにいくつかの行が記録されるはずですが、実際には保存はOKであり、デバッグログには行が書き込まれません。

<?php
class Link extends AppModel {
    var $name = "Link";
    var $belongsTo = array('Category' => array('className' => 'Category', 'foreignKey' => 'category_id'));

  public function beforeSave(){
        if ($this->data[$this->alias]['id'] == null) {
            $this->log("new record", 'debug');
            $link = $this->find('first',array('conditions' => array('Link.status = 1 AND Link.category_id = '.$this->data[$this->alias]['category_id']), 'order' => array('Link.order DESC') ));
            if (is_null($link)) {
                $this->data[$this->alias]['order'] = 1;
            }else{
                $this->data[$this->alias]['order'] = $link['Link']['order'] + 1;
            }
        }
        else {
            $this->log("old record", 'debug');
        }
        return false;
    }
}   
?>

私は次のようにコントローラーで保存を開始しています:

public function add($category_id = null)
    {
        if ($category_id == null) {
            $this->Session->setFlash(__('Category id cant be null'),'default', array('class' => 'error-message'));
            $this->redirect(array('action' => 'index', 'controller' => 'categories'));
        }
        else
        {
            if($this->request->is('post'))
            {
                $this->Link->create();
                $this->Link->set('category_id' => $category_id));
                if($this->Link->save($this->request->data))
                {
                    $this->Session->setFlash(__('The link has been saved'),'default', array('class' => 'success'));
                    $this->redirect(array('action' => 'index/'.$category_id));
                }
                else
                    $this->Session->setFlash(__('The link could not be saved. Please, try again.'),'default', array('class' => 'error-message'));
            }
            $this->set('category_id',$category_id);
        }
    }

beforeSaveStackOverflowの別の質問は、メソッドをモデルで宣言する必要があることを指摘しています。私も別のモデルで同じことをしました。

4

2 に答える 2

3

ここに、答えのためのいくつかの一般的なアドバイスとあなたのコードに関するいくつかのコメントがあります:

1)モデルコールバックまたはいずれかのモデルメソッドが機能しない場合は、デフォルトモデル(AppModel)ではなく、正しいモデルが使用されていることを確認してください。ファイル名、クラス名、拡張子(あなたの場合)、および場所を確認してください。

2)条件配列を誤って使用しています(この場合)。

array('conditions' => array('Link.status = 1 AND Link.category_id = '.$this->data[$this->alias]['category_id'])

あなたは本当にしているべきです:

array('conditions' => array('Link.status' => 1, 'Link.category_id' => $this->data[$this->alias]['category_id'])

3)リダイレクトが間違って使用されています

$this->redirect(array('action' => 'index/'.$category_id));

する必要があります:

$this->redirect(array('action' => 'index', $category_id));
于 2012-07-17T01:04:22.700 に答える
2

書かれているように、save()は常にこのbeforeSave()で失敗します。save関数が成功するには、beforeSave()がtrueを返す必要があります。実際、あなたは常にfalseを返し、保存の失敗を保証しているように見えます。

ケーキのマニュアルから:

beforeSave()がtrueを返すことを確認してください。そうしないと、保存が失敗します。

于 2015-02-23T20:56:05.777 に答える