laravel 在laravel eloquent create中保存多条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48472015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:18:07  来源:igfitidea点击:

Saving multiple records in a laravel eloquent create

phplaravel

提问by Geoff

I'm trying to save multiple records via

我正在尝试通过以下方式保存多条记录

AppSettings::create(
    [
        'name'=>'mail_host',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_port',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_username',
        'type'=>$emailsettingstype->id,
        'value'=>'',
    ],
);

But from the above, only the first array is getting created. Where am i going wrong? Any help is appreciated.

但是从上面来看,只有第一个数组被创建。我哪里出错了?任何帮助表示赞赏。

回答by Wreigh

I think this should do

我认为这应该做

AppSettings::createMany([
    [
        'name'=>'mail_host',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_port',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_username',
        'type'=>$emailsettingstype->id,
        'value'=>'',
    ],
]);

Make sure you're passing an array of arrays, not a params of array.

确保您传递的是数组数组,而不是数组参数

UPDATE, you can use Model::insert()although according to what I've read, that method doesn't create/update the timestamps.

更新,您可以使用,Model::insert()尽管根据我读过的内容,该方法不会创建/更新时间戳。

回答by Ganesh Ghalame

You can just use Eloquent::insert() linkas below:

您可以使用 Eloquent::insert()链接,如下所示:

AppSettings::insert([
    [
        'name'=>'mail_host',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_port',
        'type'=>$emailsettingstype->id,
        'value'=>'',

    ],
    [
        'name'=>'mail_username',
        'type'=>$emailsettingstype->id,
        'value'=>'',
    ],
]);

The problem with above is that it won't update timestamps, find examples here

上面的问题是它不会更新时间戳,在这里找到示例

回答by justnajm

In case some one searching for eloquent model, I used the following method:

如果有人在寻找 eloquent 模型,我使用了以下方法:

foreach($arCategories as $v)
{                
    if($v>0){
        $obj = new Self(); // this is to have new instance of own
        $obj->page_id = $page_id;
        $obj->category_id = $v;
        $obj->save();
    }
}

$obj = new Self();is a must otherwise it only saves single record when $thisis used.

$obj = new Self();是必须的,否则它只在$this使用时保存单个记录。