简体   繁体   中英

Laravel 'save()' for 'hasmany' Model

If I have a two models, with a hasMany relationship, so my Car hasmany CarOwners , I would like to use to use the firstOrCreate method to create a new car .

If I'm creating a new car then I need to create the first CarOwner too.

Without leveraging any laravel functionality, I would

  1. create a new car,
  2. get the ID of the new car object
  3. create a new CarOwner, associating it with the recently created car

Isn't there a way to do this in one go? I can do the queries to find the CarOwners of the chosen car, but I can't see how to save across multiple tables.

Refer to laravel manual .if you already created a Model for them it would be like this

car->carOwners()->save($owners)

link https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM