我不知道如何處理這個。所以我有一個模型: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倍。但我不想這樣做,因爲我不想在我的服務中到處稱呼「新」,因爲它正在扼殺依賴注入。
對不起,我沒有注意到的「創造」的方法。我應該在循環的情況下調用,而不是「保存」方法。所以它會是$ this-> myModel-> create(attr數組);在循環內。謝謝回覆 :-) – Darryldecode