在laravel eloquent创建中保存多个记录

时间:2018-01-27 02:32:04

标签: php laravel

我试图通过

保存多条记录
"=COUNTIF('Consol List'!" & Range(Cells(3, LastColumn), Cells(LR, LastColumn)).Address(0, 0) & """<>0"")-COUNTBLANK('Consol List'!" & Range(Cells(3, LastColumn), Cells(LR, LastColumn)).Address(0, 0) & ")"

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

7 个答案:

答案 0 :(得分:6)

我认为应该这样做

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(),但根据我所阅读的内容,该方法无法创建/更新时间戳。

答案 1 :(得分:2)

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

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

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

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

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

答案 2 :(得分:1)

可从laravel对此link和此documentation进行关系检查引用中找到创建多个方法createMany

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

我有两个模型PricingAvailableService模型

定价模型

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],
]);

它适用于,您也可以尝试一下。谢谢

答案 3 :(得分: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时保存单个记录。

答案 4 :(得分:0)

您可以通过以下方式进行操作:laravel 5.8

public function store(Request $request)
{
    $this->validate($request,[
        'country_id' => ['required'],
        'requirement' => ['required','max:1000'],
    ]);

    try {

        DB::beginTransaction();

        for ($i=0; $i < sizeof($request->requirement) ; $i++) {
            $req = new VisaReqModel();
            $req->country_id = $request->country_id;
            $req->requirement = $request->requirement[$i];
            $req->save();
        }

        DB::commit();

        if ($req->save()) {
            session()->flash('success','record saved successfully!');
            return redirect()->back();
        }else{
            session()->flash('error','record does not saved successfully!');
            return redirect()->back();
        }

    } catch (Exception $e) {

        DB::rollBack();
        Session::flash('error',$e->getMessage());
        return redirect()->back();
    }
}

答案 5 :(得分:0)

如果您想在播种机中存储多条记录,请使用此方法而不是 insert,因为在我的情况下,我想使用 spatie/laravel-sluggable pkg 自动创建 slug。如果您使用了 insertDB 技术,那么您还必须为 slug 字段提供值。

类别播种器

<?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); });
    }
}

答案 6 :(得分:0)

在播种机中创建一个数组并使用 Model::create() 执行 foreach。您的所有记录都将带有时间戳


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

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