0

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?

GiuServ
  • 1,215
  • 1
  • 13
  • 33

1 Answers1

0

You must use associate method.

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

Hope it help you :)

Odin Thunder
  • 3,284
  • 2
  • 28
  • 47
  • i'm not sure it works. looking at [this question](http://stackoverflow.com/questions/26160661/cant-get-laravel-associate-to-work) i should save my service model before i can call the associate. Anyway, i just tried it and it doesn't work. I also tried the reverse `$operation->service()->associate($service)`, but it doesn't save the new operations created. – GiuServ Apr 26 '17 at 12:09