Friday, August 27, 2010

Re: SaveAll and Save inserting two rows instead of one

Ah, figured it out.

http://book.cakephp.org/view/1031/Saving-Your-Data

foreach($users as $k => $user) {
foreach($stats as $stat) {
$this->Subscription->create();
$this->Subscription->set(array('statistic_id' => $stat['Statistic']
['id'], 'user_id' => $k));
$this->Subscription->save();
}
}

this is the fixed version.

It seems to me that both should work in the same way. Could some
provide some insight into why calling set for each field would result
in multiple rows on insert?


On Aug 27, 12:17 pm, Anthony <anthony.c.fra...@gmail.com> wrote:
> In my app I have users, stats and subscriptions
>
> users hasMany subscriptions
> stats hasMany subscriptions
> subscription belongsTo user and statistic
>
> I've determined all users should be required to subscribe to some
> statistics.  And am attempting to make an action I can run (just once,
> other logic will take care of the rest) to create all the required
> subscriptions.
>
> To do this I get a list of the stats where
> Statistic.required_subscription = 1 and list of each user account and
> then build the array to insert or insert each row individually.
>
> I'm using this code to put together the data and insert.  At the end n
> is equal to the number of elements in the array, (441) however the
> number of records in the DB is 882.
>
> $n = 0;
>                 foreach($users as $k => $user) {
>                         foreach($stats as $stat) {
>                                 $this->Subscription->create();
>                                 $this->Subscription->set('statistic_id', $stat['Statistic']
> ['id']);
>                                 $this->Subscription->set('user_id', $k);
>                                 $this->Subscription->save();
> $n++;
> debug($n);
>                         }
>                 }
>
> I also attempted to package all the data up into an array in the
> following format:
>
> $data['subscription'][] = array('user_id' => $uid, 'statistic_id' =>
> $sid);
> then $this->Subscription->saveAll($data['Subscription']
>
> This method worked as well but also doubled the amount of records I
> expected to be inserted.
>
> What could I possibly be doing wrong? Could this be caused by a
> "feedback look" with in how the models are related; the relations
> seems ok to me...

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

No comments: