简体   繁体   English

Laravel一对多关系插入数组

[英]Laravel one to many relationship insert array

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 我有2个型号:用户

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. 所以我有表用户的id和name列,我有id,user_id和cluster_name列的表簇。 The link between the 2 tables is the users.id and clusters.user_id 2个表之间的链接是users.id和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? 我知道如果我使用App\\User::find(1)->clusters()->saveMany(x)那么x需要是一组对象,但我想知道如何用数组直接做到这一点? 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)? 或者我需要在阵列上做一个foreach,然后逐个保存群集(从我从表单中获得的)?

Thanks. 谢谢。

Try to use the function createMany() which accepts an array as an attribute, for example: 尝试使用接受数组作为属性的createMany()函数,例如:

$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 https://laravel.com/docs/5.5/eloquent-relationships#the-create-method

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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