在Laravel Eloquent的create方法中保存多条记录

32

我正在尝试通过

保存多个记录。
AppSettings::create(
    [
        'name' => 'mail_host',
        'type' => $emailsettingstype->id,
        'value' => '',

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

但是从上面来看,只有第一个数组被创建了。我错在哪里了?希望能得到任何帮助。

6个回答

28

我认为这样就可以了

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

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

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

请确保传递的是一个数组的数组,而不是一个数组的参数

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


4
这个答案是针对 Laravel 的早期版本的,不幸的是,我已经不再跟进最新的主要版本,也不确定应该如何在最新的主要版本中完成。如果有人能够更新这个答案,那将会非常感激,如果这样做有任何价值的话。 - Wreigh
9
"Call to undefined method App\Models\Post::createMany() " 是 Laravel 8 中一个错误信息,意思是调用了未定义的方法 createMany()。 - Waleed Khaled
Model::insert() 在 Laravel 7 上可用。 - user3613026
3
此建议不适用于版本9或任何以前的Laravel版本。根据官方Laravel文档,createMany()方法可以“创建多个相关模型”,这意味着它仅适用于相关模型,而不是直接作用于模型,如上所述。 - azurecorn

24

您可以直接使用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'=>'',
    ],
]);

以上的问题在于它不会更新时间戳,您可以在这里找到示例。


6
注意:Model::insert() 不会存储 created_atupdated_at,如果需要的话,您应该自己添加它们。 - HasanAlyazidi

5

在 Laravel 中,关系的检查引用了 createMany 方法。有关此方法的更多信息,请参见此链接和来自 Laravel 的文档

到目前为止,我的示例如下所示。

我有两个模型:PricingAvailableService 模型。

Pricing 模型

namespace App;
use Illuminate\Database\Eloquent\Model;
class Pricing extends Model
{
    protected $fillable = ["name", "price"];
    public function available(){
        return $this->hasMany(AvailableService::class, "pricing_id", "id");
    }
}

AvailableServiceMode的外观如下:

namespace App;
use Illuminate\Database\Eloquent\Model;
class AvailableService extends Model
{
    protected $fillable = ["pricing_id", "service_id"];
    public function service(){
        return $this->belongsTo(Service::class, "service_id", "id");
    }
}

因此,createMany 操作看起来像这样

$insertMany = Pricing::create(['name'=>request('name')]);
$insertMany->available()->createMany([
      ['service_id'=>1],
      ['service_id'=>2],
      ['service_id'=>3],
      ['service_id'=>4],
      ['service_id'=>5],
]);

它对于IT技术相关内容来说是有效的,你也可以尝试一下。谢谢


创建了很多作品,但仍然执行了太多的SQL查询。是否有类似于关系插入的东西? - Pushkraj Jori

4
如果您希望在seeder中存储多条记录,请使用此方法,而不是使用insert,因为在我的情况下,我想要使用spatie/laravel-sluggable包自动创建slug。 如果您使用insertDB技术,则还必须为slug字段提供值。

CategorySeeder

<?php

namespace Database\Seeders;

use App\Servcategory;
use Illuminate\Database\Seeder;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $categories = [
            [
                'name' => 'Automotive',
                // 'slug' => 'automotive',
            ],
            [
                'name' => 'Business Services',
                // 'slug' => 'business-services',
            ],
            [
                'name' => 'Computer, Telecom & IT Services',
                // 'slug' => 'computer-telecom-&-it-services',
            ],
            [
                'name' => 'Education & Training',
                // 'slug' => 'education-&-training',
            ],
            [
                'name' => 'Finance',
                // 'slug' => 'finance',
            ],
            [
                'name' => 'Hospitals, Clinic, Medical',
                // 'slug' => 'hospitals-clinic-medical',
            ],
            [
                'name' => 'Real Estate, Construction, Property',
                // 'slug' => 'real-estate-construction-property',
            ],
            [
                'name' => 'Travel,Toursim & Hotels',
                // 'slug' => 'travel-toursim-&-hotels',
            ],
        ];

        // Servcategory::insert($categories);
        collect($categories)->each(function ($category) { Servcategory::create($category); });
    }
}


0
如果有人在寻找优雅的模型,我使用了以下方法:
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();是必须要使用的,否则只有在使用$this时会保存单个记录。


-2
在 Seeder 中创建一个数组,并使用 Model::create() 进行 foreach。这样,你的所有记录都将带有时间戳。

protected $array = [
    [...],
    [...],
    [...]
];

public function run()
{
    foreach ($this->array as $value) {
        Model::create($value);
    }
}


嘿,伙计,这是不正确的,因为例如如果有100000条记录,它必须运行100000个查询,对你的项目来说这是非常有害和可怕的。 - Azade

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接