2017-04-26 118 views
0

我試着存儲一個新的模型,與許多相關的新模型。Laravel雄辯:存儲與相關的新模型的新模型

我有我的服務模型

class Service extends Model{ 
    public function serviceoperations() { 
     return $this->hasMany("App\Models\ServiceOperation"); 
    } 
} 

和我ServiceOperation模型

class ServiceOperation extends Model{ 
    public function service() { 
     return $this->belongsTo("App\Models\Service"); 
    } 
} 

在我的店裏功能我正在創建一個新的服務模式,與衆多serviceoperation車型,使用交易

use App\Models\Service; 
use App\Models\ServiceOperation; 
use Illuminate\Support\Facades\DB; 

    public function store(Request $request) { 
     $service = new Service(); 
     $ops = []; 
     foreach ($operations as $operation) { 
      $op = new ServiceOperation(); 
      $ops[] = $op; 
     } 
     DB::transaction(function()use($service, $ops) { 
      $service->save(); 
      $service->serviceoperations()->saveMany($ops); 
     }); 
    } 

問題是:是否有另一種方式我的新的相關serviceoperation模型添加到我的新服務模型,並在數據庫中堅持他們在一個單一的命令?

回答

0

您必須使用associate方法。

$service->serviceoperations()->associate($serviceoperations) 

希望它可以幫助你:)

+0

我不知道它的工作原理。看看[這個問題](http://stackoverflow.com/questions/26160661/cant-get-laravel-associate-to-work)我應該保存我的服務模型,然後我可以打電話給同事。 無論如何,我只是試了一下,它不起作用。我也嘗試了相反的'$ operation-> service() - > associate($ service)',但它不保存創建的新操作。 – GiuServ