php - Laravel 4 Eloquent Model Inside loop -
i wonder how handle this. have model:
class mymodel extends eloquent { // assuming have proper codes here }
and in services lets have code:
class myservice { protected mymodel; public function __construct(mymodel $mymodel) { $this->mymodel = $mymodel; } public function savemanytimes() { // assuming have loop here needs // save many times $x = 0; $y = 5; while($x < $y){ $this->mymodel->name = 'joe'; $this->mymodel->age = 19; $this->mymodel->save(); } } }
now question is, in savemanytimes method, can see, has loop saves upto 5x. output first iteration save. why eloquent behaving that? how handle that?
but when try change code to:
// note use **new** $x = 0; $y = 5; while($x < $y){ $mymodel = new mymodel(); $mymodel->name = 'joe'; $mymodel->age = 19; $mymodel->save(); }
this works great, saves data 5x. don't want way don't want call "new" everywhere, in service, because it's killing dependency injection.
when inject mymodel __construct creating new mymodel. __construct called when instantiate myservice, 1 time. if want inject model in __construct have instantiate myservice 5 times new myservice , save 1 time in function.
Comments
Post a Comment