简体   繁体   中英

Laravel how to save multiple related models?

My form posting this data

{
  "name": "Company Name1",
  "contacts": [ 
    {
      "name":"John Doe",
      "phone":"123123"
    },
    {
      "name":"John Doe 2",
      "phone":"123123"
    }
  ]
}

I want to create a company with the name and then for each contact in contacts new contact relation which is related to this company.

Do you guys have any idea about how can I do that with createMany or something like that?

Solution

Guys, I realized that I forgot to send specific required data with the form after I fix that I realized that I'm able to store data with this code

$company->contacts()->createMany($request->contacts);

and this is the last version of the code

$arr = $request->safe()->only(['contacts']);
$company = Company::create($request->safe()->only(['name']));
$company->contacts()->createMany($arr['contacts']);

You can bulk insert records using insert method in laravel

Create a new company record and then use that company's id to insert record in contact table

$company = new Company;
$company->name = "Your Company Name";
$company->save();
$data = [
           [ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],
           [ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ]
        ];
Contact::insert($data);

I solved the situation apparently I could just store the data like this

$company->contacts()->createMany($request->contacts);

But when sending the data, I forgot to send the required input, so it was not working because of that.

Multiple ways to do that. On way would be to use the saveMany Method:

$company = new Company;
$company->name = "Your Company Name";
$company->save();

$company->contacts()->saveMany([
    new App\Models\Contact([ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],),
    new App\Models\Contact([ "name"=>"John Doe", "phone"=>"123123","company_id"=> $company->id ],),
]);

https://laravel.com/docs/5.5/eloquent-relationships#the-save-method

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