gpt4 book ai didi

php - Laravel Eloquent - 一次插入多个对象

转载 作者:行者123 更新时间:2023-11-29 03:33:53 26 4
gpt4 key购买 nike

我正在通过读取 CSV 文件创建多个(有时数百个,有时数千个)Eloquent 对象。

以这个循环为例:

$cities = [];
while ($city = readNextCity()) {
$cities[] = $city;
}
// ok how do I save all $cities without calling $city->save() on each?

我们知道在一次查询中插入多行比每次查询插入 1 行要高效得多。但是,有没有一种方法可以一次插入多个 Eloquent 对象,以便将它们转换为一个查询? (如果没有,我不介意写它,但我不想重复努力)。

最佳答案

我认为您可以为此使用查询生成器。

$cities = array();
$i=0;
while ($city = readNextCity()) {
$cities[$i++] = array('city' => $city);
}

DB::table('city')->insert($cities);

希望这会有所帮助。

关于php - Laravel Eloquent - 一次插入多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26343646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com