将模型保存在每个循环的外部



假设模型订单

class Order extends Model {
use HasFactory;
protected $table = 'order';
protected $primaryKey   = 'id';
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
public function extra(){
return $this->hasOne(Extra::class);
}
public function products(){
return $this->hasMany(Product::class);
}
}

Model Extra

class Extra extends Model {
use HasFactory;
protected $table = 'extra';
protected $guarded = [];
public function order(){
$this->belongsTo(Order::class);
}
}

型号产品

class Product extends Model {
use HasFactory;
protected $table = 'product';
protected $guarded = [];
public function order(){
return $this->belongsTo(Order::class);
}
}

现在,我从API接收数据。有了这些数据,我想提供模型,然后将信息存储到DB中。

atm的方法是:

foreach ($list as $item) {
$order = new Order();
$order->id = $item['id'];
$order->title = $item['title'];
$order->save();
$extra = new Extra();
$extra->foo= $item['path']['to']['foo'];
$extra->bar= $item['path']['to']['bar'];
$order->extra()->save($extra)

$order->products()->createMany($item['path']['to']['products']);
}

问题是,此代码为每个循环保存三次,一次用于订单,一次为额外,一次针对产品。我想知道是否有另一种方法可以用来收集内部和外部的数据,以制作类似的东西

Order::insert($array_of_data);

我想它会是这样的,试试看,如果不起作用,请告诉我我会删除答案

$orders = [];
$extras = [];
$products = [];
foreach ($list as $item) {

$orders[] = [
'id' => $item['id'],
'title' => $item['title'],
];
$extras[] = [
'foo' => $item['path']['to']['foo'],
'bar' => $item['path']['to']['bar'],
];
$products[] = [
'order_id' => $item['id'],
'foo' => $item['path']['to']['products']['foo'] // or data it has
];
}
Order::insert($orders);
Extra::insert($extras);
Product::insert($products); // make sure each product has order id and data which is not visible here

我还建议考虑将$list转换为集合,然后对其进行迭代,如果数据很大,您可以使用LazyCollection,它与集合相同,但更适合处理较大的数据集

下面是一个使用懒惰收集的例子

LazyCollection::make($list)
->each(function (array $item) {
$order = Order::create(
[
'id' => $item['id'], 
'title' => $item['title']
],
);

Extra::create(
[
'order_id' => $item['id'], 
'foo' => $item['path']['to']['foo'],
'bar' => $item['path']['to']['bar'],
],
);

$order->products()->createMany($item['path']['to']['products']);
});

虽然它不一定一次创建很多,但它是内存的救星,并且会很快处理

最新更新