【问题标题】:Laravel insert collection in dbLaravel 在数据库中插入集合
【发布时间】:2017-06-21 13:58:17
【问题描述】:

我已使用以下方法从 db 中检索了一些数据:

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get();

我想在另一个表中插入我检索到的内容,例如:

DB::table('tmp_other')->insert($filtered);

但我收到了错误:

Type error: Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, object given

哪种方法最好?

【问题讨论】:

  • DB::table('tmp_other')->insert($filtered->toArray()); 应该可以工作。
  • @StefanoMaglione 好吧...你明白了吗,错误信息中写了什么?
  • Eloquent 标签在这里不适用吗?

标签: php laravel-5 eloquent


【解决方案1】:

执行这种直接插入的 SQL 方式更像是原生的:

DB::insert(
      "INSERT INTO tmp_other (type,description,note) 
       SELECT DISTINCT type,description,note FROM tmp_table"
); 

这将避免整个传输到网络服务器/传输回 SQL 服务器进程。

【讨论】:

  • 最简单的想法就是最好的!
【解决方案2】:

这将为您解决问题,试试这个:)

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get();
$filtered->toArray();

DB::table('tmp_other')->insert($filtered);

【讨论】:

  • 我试过了,但是不行,stdClass类的对象不能转换成字符串
【解决方案3】:

这样就可以了:)

$filtered = DB::table('tmp_table')->distinct()->select('type','description','note')->get()->toArray();
$to_fill = [];
foreach($filtered as $record) {
  $to_fill[] = (array)$record;
}

DB::table('tmp_other')->insert($to_fill);

【讨论】:

    【解决方案4】:

    你可以这样做一行,像这样:

    Region::insert($tempCollection->toArray());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2020-07-05
      • 2010-11-18
      • 2020-08-26
      • 1970-01-01
      相关资源
      最近更新 更多