使用Laravel-7模型保存这些数据有问题。
这是我的资料
$supplier = [
'name' => 'Supplier 1',
'pic' => [
[
'name' => 'PIC 1',
'phone_number' => [
['number' => '111111'],
['number' => '123456']
]
],
[
'name' => 'PIC 2',
'phone_number' => [
['number' => '222222']
]
]
]
];这是我的模特Supplier.php
// Supplier.php
public function supplier_pic()
{
return $this->hasMany('SupplierPIC');
}以及其他模型
// SupplierPIC.php
public function supplier()
{
return $this->belongsTo('Supplier');
}
public function pic_phone_number()
{
return $this->hasMany('SupplierPICPhoneNumber');
} // SupplierPICPhoneNumber.php
public function supplier_pic()
{
return $this->belongsTo('SupplierPIC');
}如何将这些数据保存在控制器上?谢谢
发布于 2020-07-03 11:53:13
你只需要把它分解成它的组成对象。
在您的例子中,它是一个Supplier对象和两个SupplierPIC对象,每个对象都有一个SupplierPICPhoneNumber
$supplier = Supplier::firstOrCreate([
'name' => 'Supplier 1'
]);collect($data['pics'])->each(function ($pic) use ($supplier) {
// Create the PIC
$x = SupplierPIC::create([
'name' => $pic['name']
]);
// Attach it to the supplier
$supplier->supplier_pic()->save($x);
// Attach phone numbers
collect($pic['phone_number'])->each(function ($number) use ($x) {
// Create the PIC Phone number
$y = SupplierPICPhoneNumber::create([
'number' => $pic['number']
]);
// Attach the number to the PIC
$x->pic_phone_number()->save($y);
});
});建议
,
pic_phone_number)pic_phone_numbers )命名使用hasMany类型关系的事物,您需要一个完整的SupplierPICPhoneNumber模型吗?json列可能更适合。https://stackoverflow.com/questions/62710928
复制相似问题