【问题标题】:Laravel insert into db using eloquentLaravel 使用 eloquent 插入数据库
【发布时间】:2019-06-24 21:16:45
【问题描述】:

我正在尝试使用 laravel db 方法插入到我的数据库中,我可以使用以下代码插入数组:

if(!empty($data) && $data->count()){

    foreach ($data as $key => $value) {
        $insert[] = [
        'Number' => $value->number,
        'Full_Name' => $value->full_name,
        'Type' => $value->type,
        'Email' => $value->email,
        ];  
    }

    if(!empty($insert)){

        $insertData = DB::table('import')->insert($insert);
        if ($insertData) {
            Session::flash('success', 'Your Data has successfully imported');
        }else {                        
            Session::flash('error', 'Error inserting the data..');
            return back();
        }
    }
}

在这里我可以使用插入数组插入值,但我想使用 eloquent create 方法插入这个值是这样的吗:

$insertData = Import::create($insert);

我想用这个方法:

firstOrNew

如何使用 eloquent 方法插入数据库,如果有任何重复,它应该会抛出错误。

导入型号代码:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Import extends Model
{
    protected $table = 'imports';
    protected $fillable =  [
      'id',
      'Number',
      'Full_Name',
      'Type',
      'Email',
      'created_at',
      'updated_at'
    ];
}

我使用的是 laravel 5.2

【问题讨论】:

  • 您可以使用 create 插入数据数组。您也可以使用$import = new Import(); 来获取模型。然后你可以做$import->fill($request->input())->save();
  • $insertData = Import::create($insert);这个不工作
  • 您是否将protected $fillable = [] 设置在模型顶部? Take a look here 在批量分配下。
  • 是的,我设置了受保护的可填充,我收到错误不是空违规:7 错误:列中的空值
  • 如果$insert 是一个数组数组(顺便说一句,这是一个可怕的名字),那么array_walk($insert, function($import) { Import::create($import); })

标签: laravel eloquent


【解决方案1】:

我使用 alexkb 注释解决了这个问题,我正在使用这个代码:

array_walk($insert, function($import) { Import::create($import); })

这个正在工作

【讨论】:

    【解决方案2】:

    你可以使用firstOrCreate避免重复,第一个参数用于查找记录,第二个用于新记录,但不用于搜索

    $import= Import::firstOrCreate([
        'email' => 'email@email.com'
    ], [
        'Full_Name' => 'Nilay Singh',
        'Type' => 'Type'
    ]);
    

    【讨论】:

    • $insertData = DB::table('import')->insert($insert);这是有效的,但创建不能使用相同的数组我得到空错误
    • 嗯,显示什么错误?? DB::table->insert 不要使用 Model 进行插入... $fillable 或 $guarded 属性没有效果,但是使用 Import::create() 并且您的 $fillable 数组应该可以工作..
    猜你喜欢
    • 2019-05-25
    • 2015-09-19
    • 2018-07-09
    • 2014-11-02
    • 2016-08-16
    • 1970-01-01
    • 2014-05-19
    • 2021-11-16
    • 2019-08-01
    相关资源
    最近更新 更多