Hello. How in laravel can you add values ​​to a database that come in an array on hasMany links? Analog attach on a belongsToMany connection.

 $person = Person::create($request->all()); $person->fields->createmany($request->fields); // выходит ошибка 

$request->fields is a bulk. Everything looks like this

 array( 'first_name' => 'Test' 'fields' => array( 0 => 'asdasd', 1 => 'asda312312sd', 2 => 'a123123sdasd', ) ) 

I know about saveMany but he also gives errors

  • and sync and attach accept the same array - Orange_shadow
  • Yes. They take an array on the belongsToMany connection, but there is no link on the hasMany connection. And the fact that there is is create / save / saveMany / createMany . But it did not come out with them. I solved the problem yesterday. - Alex_01
  • github.com/laravel/framework/issues/3251 , read what Teo writes. Drove about this - Orange_shadow

1 answer 1

Decided so

 /** * Attach related model * * @param array $aGroup * @return AttributeGroup|array */ public function attachRelated(Array $aGroup) { $instances = []; foreach($aGroup as $group) { $instances[] = new AttributeGroup(['name' => $group]); } return $instances; } 

And now we do it

 $person = Person::create($request->all()); if($request->fields) // если заполнены данные в поле fields[] { $person->fields()->saveMany($this->attachRelated($request->fields)); }