【发布时间】:2022-04-16 03:02:04
【问题描述】:
目前,每当我需要创建具有子模型的 Laravel 模型的新实例时,我需要在控制器中创建模型,然后在控制器中循环所有子模型并将它们附加到父模型。该模型能够将自身导出到包含其子项的数组,因此您会认为您也可以导入数组来创建模型对象。
是否可以将数组传递给 Laravel 模型并让它自动创建自己的子模型?
【问题讨论】:
标签: laravel model controller parent-child laravel-5.7
目前,每当我需要创建具有子模型的 Laravel 模型的新实例时,我需要在控制器中创建模型,然后在控制器中循环所有子模型并将它们附加到父模型。该模型能够将自身导出到包含其子项的数组,因此您会认为您也可以导入数组来创建模型对象。
是否可以将数组传递给 Laravel 模型并让它自动创建自己的子模型?
【问题讨论】:
标签: laravel model controller parent-child laravel-5.7
在您的模型上放置一个方法,该方法接受子对象数据数组并创建和关联它们。然后你只需要创建主模型并在其上调用子创建方法。
class MyModel
{
...
public function createChildren($childData)
{
//create and associate children
}
}
class MyController
{
...
public function create()
{
...
$myModel = MyModel::create($modelData);
$myModel->createChildren($childData);
}
}
【讨论】:
这应该适合你,你可以发送带有模型值和子值的数组
public static function createWithChildren(array $values)
{
// Set all the children ellements you can fill
$childs = [
'comments' => null,
'links' => null
];
// Remove the values from childs and add it to another temp array
foreach ($childs as $child => $values){
if (Arr::has($values, $child)) {
$childs[$child] = Arr::pull($values, $child);
}
}
// Create model without the related values and save
$model = new self();
$model = $model->fill($values);
$model->save();
// After save, set all children values
foreach (array_filter($childs) as $child => $values) {
$model->$child()->create($values);
}
}
【讨论】: