i'm tryint to store a new Model, with many related new models.
I have my Service model
class Service extends Model{
public function serviceoperations() {
return $this->hasMany("App\Models\ServiceOperation");
}
}
and my ServiceOperation model
class ServiceOperation extends Model{
public function service() {
return $this->belongsTo("App\Models\Service");
}
}
in my store function i'm creating a new service model, with many serviceoperation models, using a transaction:
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);
});
}
My Question is: Is there another way to add my new related serviceoperation models to my new service model, and persist them in the database in a single command?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire