cake-php
[Arriba] [Todas las Listas]

Re: Consigue registro viejo en beforeSave cuando actualizando (haciendo

To: cake-php@xxxxxxxxxxxxxxxx
Subject: Re: Consigue registro viejo en beforeSave cuando actualizando (haciendo un $esto->encontrar() dentro de beforeSave callback)
From: Vanja Dizdarević <lex.non.scripta@xxxxxxxxx>
Date: Sat, 29 Jun 2013 12:14:31 -0700 (PDT)
Delivery-date: Sat, 29 Jun 2013 15:14:43 -0400
Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=googlegroups.com; s=20120806; h=x-beenthere:date:from:to:message-id:in-reply-to:references:subject :mime-version:x-original-sender:reply-to:precedence:mailing-list :list-id:x-google-group-id:list-post:list-help:list-archive:sender :list-subscribe:list-unsubscribe:content-type; bh=iJOXM5PTTJBrt0OuWCth8SCVQ75HG2UT/mm3pqZ2xnA=; b=LZd9dseXGhAzzs4nQf+yGyTsY0WvlQUdfz25N58DoRZ8cx/u/lmaDnXsU/ah/Db4O5 cHCr7vnRB5nXzVs/9Q0GDvbxmQtgvvyokk914R9wuMiizNaPE3ydXuF4Mb7a9vVroRKQ 4FTwHZ73fEl+ItmKvMwPh505XiBbjpvG8mcXya5JQWn+ZdwRnL9GP5zzXRtpb82r5vSr g0fs4e+Cf96a57c2DqkloewwCAyNQ+8ePEeowd6eRJA5OQsZmZYsVqYzo+OPhcnfcOU4 4sxbPJb0F8H0jNNUw8Q54eIj+ktOOe029nNJffiHBh1V/rUbRiNsBMCFDYawVWmbGuCV bedw==
Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=x-beenthere:date:from:to:message-id:in-reply-to:references:subject :mime-version:x-original-sender:reply-to:precedence:mailing-list :list-id:x-google-group-id:list-post:list-help:list-archive:sender :list-subscribe:list-unsubscribe:content-type; bh=iJOXM5PTTJBrt0OuWCth8SCVQ75HG2UT/mm3pqZ2xnA=; b=cgFoEzLXK4pteT3FDcG4KnpQJAOXOEW5M5HzG9lh0qFXhfNgI700IJH1xcPdsHke+4 pMnMtfSyYvOn5bqRXzp20XQ7r/uQW40X646P1by8pXCtO4hy86dTQv71+jI+mzWztISH s+NbJJqPZbKUdsq2DZADLLZpeqJ0vtprTD6NaHWYEYZXLe166pF1Bx9+6g7qCU060rM6 0fl7SwSzS33jW/fqvOJyUqL7PPJyUh5urZ6YFEGmXEozGxTFT7ALJRpGqmC7pj4XZ6WP mWxslV7ANmCxNJSFEsQqkd17mUCJdN6e0ZQCKbN7lQQBgK0WIJl/MLI6ZKnLsUMy7Uj2 o0qg==
Envelope-to: traductor@xxxxxxxxxxx
In-reply-to: <CAM39fjy+1iTQPM0UKNZnQv1rv5dPb1b5GZ6pJu+wswW9O0wrmA@mail.gmail.com>
List-archive: <http://groups.google.com/group/cake-php>
List-help: <http://groups.google.com/support/>, <mailto:cake-php+help@googlegroups.com>
List-id: <cake-php.googlegroups.com>
List-post: <http://groups.google.com/group/cake-php/post>, <mailto:cake-php@googlegroups.com>
List-subscribe: <http://groups.google.com/group/cake-php/subscribe>, <mailto:cake-php+subscribe@googlegroups.com>
List-unsubscribe: <http://groups.google.com/group/cake-php/subscribe>, <mailto:googlegroups-manage+1003367825667+unsubscribe@googlegroups.com>
Mailing-list: list cake-php@xxxxxxxxxxxxxxxx; contact cake-php+owners@xxxxxxxxxxxxxxxx
References: <87ea05b6-68aa-41d1-9a64-4ec3b8771d82@googlegroups.com> <CAM39fjy+1iTQPM0UKNZnQv1rv5dPb1b5GZ6pJu+wswW9O0wrmA@mail.gmail.com>
Reply-to: cake-php@xxxxxxxxxxxxxxxx
Sender: cake-php@xxxxxxxxxxxxxxxx
*Thanks *MorFer, que es una solución sencilla, pero siente como *meddling con Modelo. 
En el punto del encontrar, el modelo es en el salvar el ciclo y yo no saben lo que más un encontrar() podría cambiar en él.

*Btw, *$esto->dato* Y *$esto->*id* tendría que ser salvado. El *id *se tendría que quedar 
igual, pero nunca sabes. 

Esto siente más limpio, pero estoy preguntándome sobre el elevado:

            $Modelo = *ClassRegistry::*init('Usuario');
            $consulta = [
                 '*recursive' => 0, 
                 'condiciones' => [$esto->*alias.'.'.$Esto->*primaryKey => 
$esto->dato[$esto->*alias][$esto->*primaryKey]]
            ];
            $*oldData = $Modelo->encontrar('primero', $consulta);


En sábado, junio 29, 2013 8:35:04 PM *UTC+2, *MorFer escribió:
>
> *Hi.
>
> Por qué  no salvas $esto->dato en otro *var antes de llamar *findById()?
> Algo así:
>
> Usuario de clase extiende *AppModel
>    #adj_nom #público *beforeSave($opciones)
>        //#pro_verbcj #ser un actualizar?
>        Si (*isset($esto->dato[$esto->*alias][$esto->*primaryKey]))
>             //#adj_nom #leer
>             $*newdata = $esto->dato;
>             $*oldData = 
> $esto->*findById($esto->dato[$esto->*alias][$esto->*primaryKey]); 
>               //^^^ aquí el problema! ^^^
>             Si ($*oldData[$esto->*alias]['*username_actualiza_cuenta'] >= 3)
>                #verbcj falso;
>             }
>             más
>               $#prn->dato = $*newdata;
>               $esto->dato[$esto->*alias]['*username_actualiza_cuenta'] = 
> $*oldData[$esto->*alias]['*username_actualiza_cuenta'] + 1;
>             }
>        }
>    }
> }
>
> Es allí cualquier asunto que hace esto?
>
> --
> *Renato *Freire
>
>
>
>
> En Sentado, *Jun 29, 2013 en 2:53 PM, *Vanja *Dizdarević <lex.non...@xxxxxxxxx<*javascript:>
> > escribió:
>
>> Cuando actualizando una fila, deseo leer el "dato" viejo antes de salvar el 
>> registro actual.
>>
>> Aquí un ejemplo simplificado:
>>
>> código de Controlador:
>> $esto->Usuario->salvar(['*id' => 3, '*username' => 'un-nuevo-*username']);
>>
>> código de Modelo:
>> Usuario de clase extiende *AppModel
>>    #adj_nom #público *beforeSave($opciones)
>>        //#pro_verbcj #ser un actualizar?
>>        Si (*isset($esto->dato[$esto->*alias][$esto->*primaryKey]))
>>             //#adj_nom #leer
>>             $*oldData = 
>> $esto->*findById($esto->dato[$esto->*alias][$esto->*primaryKey]); 
>>               //^^^ aquí el problema! ^^^
>>             Si ($*oldData[$esto->*alias]['*username_actualiza_cuenta'] >= 3)
>>                #verbcj falso;
>>             }
>>             más
>>               $#prn->dato[$esto->*alias]['*username_actualiza_cuenta'] = 
>> $*oldData[$esto->*alias]['*username_actualiza_cuenta'] + 1;
>>             }
>>        }
>>    }
>> }
>>
>> El problema es, que $esto->*findById (o ninguno otra operación LEÍDA) llena 
>> el actual $esto->dato con el dato leído, el cual ruinas la corriente actualiza. 
>> Así que mi *gut me dice a *instantiate un modelo de Usuario nuevo dentro del *beforeSave 
>> (no *optimal) o a *somehow utiliza el *DataSource directamente sin todo 
>> el *callbacks y Modelo *instantiation.
>>
>> El real *scenario realmente tiene que ser dentro del *beforeSave *callback, 
>> porque la lógica es requerida para cada modificación.
>>
>> *Thanks!
>>
>> -- 
>> Gustarnos en *FaceBook *https://www.facebook.com/*CakePHP
>> nos Encuentra en *Twitter *http://*twitter.*com/*CakePHP
>>  
>> --- 
>> Recibiste este mensaje porque eres *subscribed al *Google Grupos 
>> "*CakePHP" grupo.
>> A *unsubscribe de este grupo y la parón que recibe *emails de él, enviar un 
>> *email a pastel-*php+u...@xxxxxxxxxxxxxxxx <*javascript:>.
>> A correo a este grupo, envía *email a cake...@xxxxxxxxxxxxxxxx<*javascript:>
>> .
>> Visita este grupo en *http://grupos.*google.*com/Pastel/de grupo-*php.
>> Para más opciones, visita *https://grupos.*google.*com/Los Grupos/optan_fuera.
>>  
>>  
>>
>
>

-- 
Gustarnos en *FaceBook *https://www.facebook.com/*CakePHP
nos Encuentra en *Twitter *http://*twitter.*com/*CakePHP

--- 
Recibiste este mensaje porque eres *subscribed al *Google Grupos "*CakePHP" grupo.
A *unsubscribe de este grupo y la parón que recibe *emails de él, enviar un *email a pastel-*php+unsubscribe@xxxxxxxxxxxxxxxx.
A correo a este grupo, envía *email a pastel-php@xxxxxxxxxxxxxxxx.
Visita este grupo en *http://grupos.*google.*com/Pastel/de grupo-*php.
Para más opciones, visita *https://grupos.*google.*com/Los Grupos/optan_fuera.


Thanks MorFer, that is a simple solution, but it feels like meddling with 
Model. At the point of the find, the model is in the save cycle and I don't 
know what else a find() might change in it.

Btw, *$this->data* AND *$this->id* should be saved. The id *should* stay 
the same, but you never know. 

This feels cleaner, but I'm wondering about the overhead:

            $Model = ClassRegistry::init('User');
            $query = [
                 'recursive' => 0, 
                 'conditions' => [$this->alias.'.'.$this->primaryKey => 
$this->data[$this->alias][$this->primaryKey]]
            ];
            $oldData = $Model->find('first', $query);


On Saturday, June 29, 2013 8:35:04 PM UTC+2, MorFer wrote:
>
> Hi.
>
> Why don't you save $this->data in another var before calling findById()?
> Something like this:
>
> class User extends AppModel {
>    public function beforeSave($options){
>        //is it an update?
>        if (isset($this->data[$this->alias][$this->primaryKey])) {
>             //read record
>             $newdata = $this->data;
>             $oldData = 
> $this->findById($this->data[$this->alias][$this->primaryKey]); 
>               //^^^ here's the problem! ^^^
>             if ($oldData[$this->alias]['username_update_count'] >= 3){
>                return false;
>             }
>             else {
>               $this->data = $newdata;
>               $this->data[$this->alias]['username_update_count'] = 
> $oldData[$this->alias]['username_update_count'] + 1;
>             }
>        }
>    }
> }
>
> Is there any issue doing this?
>
> --
> Renato Freire
>
>
>
>
> On Sat, Jun 29, 2013 at 2:53 PM, Vanja Dizdarević <lex.non...@xxxxxxxxx<javascript:>
> > wrote:
>
>> When updating a row, I wish to read the "old" data before saving the 
>> current record.
>>
>> Here's a simplified example:
>>
>> Controller code:
>> $this->User->save(['id' => 3, 'username' => 'a-new-username']);
>>
>> Model code:
>> class User extends AppModel {
>>    public function beforeSave($options){
>>        //is it an update?
>>        if (isset($this->data[$this->alias][$this->primaryKey])) {
>>             //read record
>>             $oldData = 
>> $this->findById($this->data[$this->alias][$this->primaryKey]); 
>>               //^^^ here's the problem! ^^^
>>             if ($oldData[$this->alias]['username_update_count'] >= 3){
>>                return false;
>>             }
>>             else {
>>               $this->data[$this->alias]['username_update_count'] = 
>> $oldData[$this->alias]['username_update_count'] + 1;
>>             }
>>        }
>>    }
>> }
>>
>> The problem is, that $this->findById (or any other READ operation) fills 
>> the current $this->data with the read data, which ruins the current update. 
>> So my gut tells me to instantiate a new User model inside the beforeSave 
>> (not optimal) or to somehow use the DataSource directly without all the 
>> callbacks and Model instantiation.
>>
>> The real scenario really has to be inside the beforeSave callback, 
>> because the logic is required for every modification.
>>
>> Thanks!
>>
>> -- 
>> Like Us on FaceBook https://www.facebook.com/CakePHP
>> Find us on Twitter http://twitter.com/CakePHP
>>  
>> --- 
>> You received this message because you are subscribed to the Google Groups 
>> "CakePHP" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to cake-php+u...@xxxxxxxxxxxxxxxx <javascript:>.
>> To post to this group, send email to cake...@xxxxxxxxxxxxxxxx<javascript:>
>> .
>> Visit this group at http://groups.google.com/group/cake-php.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>  
>>  
>>
>
>

-- 
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

--- 
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@xxxxxxxxxxxxxxxx.
To post to this group, send email to cake-php@xxxxxxxxxxxxxxxx.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.


<Anterior por Tema] Tema Actual [Siguiente por Tema>