2014-03-06 101 views
0

我不知道如何處理這個。所以我有一個模型:Laravel 4雄辯模型內循環

class myModel extends Eloquent { 

// assuming I have the proper codes here 

} 

在我的服務可以說我有這樣的代碼:

Class myService 
{ 

    protected myModel; 

    public function __construct(myModel $myModel) 
    { 
     $this->myModel = $myModel; 
    } 

    public function saveManyTimes() 
    { 
     // assuming i have to loop here for something that needs to be 
     // save many times 
     $x = 0; 
     $y = 5; 
     while($x < $y){ 

      $this->myModel->name = 'joe'; 
      $this->myModel->age = 19; 
      $this->myModel->save(); 

     } 

    } 

} 

現在的問題是,在saveManyTimes方法,你可以看到,它有一個循環,將 節省高達5倍。但是輸出是唯一的第一個迭代就是保存。爲什麼雄辯的行爲就像那樣?你如何處理?

但是當我嘗試將代碼更改爲:

 // note I use **new** 
     $x = 0; 
     $y = 5; 
     while($x < $y){ 

      $myModel = new myModel(); 
      $myModel->name = 'joe'; 
      $myModel->age = 19; 
      $myModel->save(); 

     } 

這個偉大的工程,它保存數據的5倍。但我不想這樣做,因爲我不想在我的服務中到處稱呼「新」,因爲它正在扼殺依賴注入。

回答

0

當您將myModel注入__construct時,您基本上正在創建一個新的myModel。但是__construct僅在實例化myService時調用,所以只有一次。如果你想在__construct中注入模型,你將不得不使用新的myService實例化myService 5次,並且只保存一次函數。

+0

對不起,我沒有注意到的「創造」的方法。我應該在循環的情況下調用,而不是「保存」方法。所以它會是$ this-> myModel-> create(attr數組);在循環內。謝謝回覆 :-) – Darryldecode

0

我看着辦吧,在我的服務:

Class myService 
{ 

    protected myModel; 

    public function __construct(myModel $myModel) 
    { 
     $this->myModel = $myModel; 
    } 

    public function saveManyTimes() 
    { 

     $x = 0; 
     $y = 5; 
     while($x < $y){ 

      // instead of doing this 
      $this->myModel->name = 'joe'; 
      $this->myModel->age = 19; 
      $this->myModel->save(); 

      // this should be this way when inside a loop cases 
      $this->myModel->create(array(
      'name' => 'joe', 
      'age' => 19 
     )); 


     } 

    } 

}