开发者

CakePHP beforeSave & HABTM

开发者 https://www.devze.com 2023-03-28 00:29 出处:网络
I\'m trying to write some beforeSave logic in CakePHP 2.0 beta. Basically I want the user to be able to submit some text for tag-like functionality. The beforeSave function would search a related tabl

I'm trying to write some beforeSave logic in CakePHP 2.0 beta. Basically I want the user to be able to submit some text for tag-like functionality. The beforeSave function would search a related table, if the tag exists just link it to the primary record, and if not, create the new tag & then link it.

So here's my function (in beforeSave):

function beforeSave() {
    if(!empty($this->data['Term']) && isset($this->Term)){
       $terms = $this->Term->find('list');
       $terms = array_flip($terms);

       foreach($this->data['Term'] as $key => $term){
           if(!empty($terms[$term['name']])){
               $this->data['Term']['Term'][$key]['id'] = $terms[$term['name']];
               unset($this->data['Term'][$key]);
           }else{
               $this->Term->create();
               $this->Term->save(array('Term' => array('name' => $term['name'])));
               $this->data['Term']['Term'][$key]['id'] = $this->Term->id;
               unset($this->data['Term'][$key]);
           }
       }
   }

   return true;
}

This basically works the way I want, creating records where necessary and finding the existing records, creating an array like this:

Array
(
    [Project] => Array
        (
            [id] => 2
            [title] => Project Title
            ...
        )

    [Term] => Array
        (
            [Term] => Array
                (
                    [0] => Array
                        (
                            [id] => 10
                        )

                    [1] => Array
                        (
                            [id] => 2
                        )

                )

        )

)

It also successfully 开发者_JS百科saves the data in the primary model (Project). But the associations under [Term][Term] are ignored. I'm pretty sure this is the correct array structure to save HABTM associations.

Anyone see what is wrong with this?


in the view you should have 1 input text $form->input('terms'); so the user can enter all the tags. So in beforeSave, you would have a string of the tags (or terms), you might want to slice it out to array, find('list') of the terms, and some array intersect or something. But in the end, you need the data to look something like this to use saveAll:

Array
(
[Project] => Array
    (
        [id] => 2
        [title] => Project Title
        ...
    )
[Term] => Array
    (
        [Term] => Array
            (
                [0] => 10 // id of the tag
                [1] => 2
            )
    )

)

0

精彩评论

暂无评论...
验证码 换一张
取 消