I get from my form page an array of values in the form of:
"managed_cluster" => array:2 [▼
0 => "Benelux"
1 => "Germany & Austria"
]
I have 2 models: User
public function clusters()
{
return $this->hasMany('App\Cluster');
}
So I have the table users with id and name column and I have the table clusters with id, user_id and cluster_name column. The link between the 2 tables is the users.id and clusters.user_id
I know that if I use App\\User::find(1)->clusters()->saveMany(x)
then x needs to be a set of objects but I was wondering how I could do that straight with the array? Or do I need to do a foreach on the array and then save the clusters one by one (from what I got from the form)?
Thanks.
Try to use the function createMany() which accepts an array as an attribute, for example:
$user = App\User::find(1);
$user->clusters()->createMany([
[
'cluster_name' => 'cluster1',
],
[
'cluster_name' => 'cluster2',
],
]);
More info:
https://laravel.com/docs/5.5/eloquent-relationships#the-create-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.