Friday, June 4, 2010

Saving multiple rows of key-value pairs during a single update?

Well my last question here turned out to be between keyboard and
chair, so hopefully this isn't quite as silly a question!

I am learning Cake and building a custom user authentication system
(who isn't?). I am trying to use two separate tables to store data,
the User Model table as parent which stores only mission critical data
(login, password, email, created, etc), and a MetaUser model table
which is built around key value pairs (meta_id, user_id, meta_key,
meta_value).

Upon registration I have two pieces of meta information I would like
to store - the activation code and an optin for receiving
communication from site admins. I have built the forms as instructed
by the Cake Book in order to use saveAll() in my Register action. The
problem is that this results in the following array:

Array
(
[MetaUser] => Array
(
[optin] => 1
[activation_code] => 9c1a26272907d4196a7bf39d
[user_id] => 17
)
)

This obviously won't save since there is no optin or activation_code
column in the MetaUser table. So I tried creating a beforeSave() under
the presumption that if this was a numerical array it might try and
add multiple rows on its own;

public function beforeSave() {

if ( isset( $this->data['MetaUser']['user_id'] ) ) {

$userid = $this->data['MetaUser']['user_id'];

$new = array();
$i = 0;

foreach ( $this->data['MetaUser'] as $k => $v ) {
$new[$i]['user_id'] = $user_id;
$new[$i]['meta_key'] = $k;
$new[$i]['meta_value'] = $v;
$i++;
}

$this->data['MetaUser'] = $new;

}

return true;

}

But apparently it doesn't work that way. I'm going to try it next
using distinct save()'s for $this->User and $this->MetaUser but am I
missing something else that I should be doing instead? I want to
create a MetaUser model where I can save each entry (even if multiple
are coming from one form) as separate rows based on the key => value
pair setup.

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate