如何在 Laravel 中插入一对多关系

How to insert a one to many relationship in Laravel

我在 Home 模型和 Phones 模型之间存在一对多关系

public function phones() {
    return $this -> hasMany(Phone::class);
}

并且在 Phone 模型中:

public function homes() {
    return $this -> belongsTo(Home::class);
}

现在在我的控制器中,当我插入 Home 时,我想用它来向 Phone table 添加无限的数字 [=18] =] 共 Home 个。这是我现在插入的方式:

public function store(StoreHome $request) {
    $validated = $request -> all();
    if (!$validated) {
        return $this -> sendError('Validation Error.', $validated -> errors());
    }

    $home = Home::create($validated);
    return new HomeResource($home);
}

现在我想知道如何在 phone table 和 realtionship 中插入 Home 和许多 Phones

既然你已经创建了你的主页,你可以在关系上使用 savesaveMany :

$home->phones()->saveMany([
    new App\Phone(['phone' => '039049230490']),
    new App\Phone(['phone' => '039049223132']),
]);

您可以在这里找到所有文档:https://laravel.com/docs/5.8/eloquent-relationships#the-save-method

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);

有关详细信息,请阅读文档 https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models

更新示例:

假设您使用多个输入字段来输入数字。

<input name="numbers[]">
<input name="numbers[]">

$phones = [];
$numbers = $request->input('numbers');
foreach($numbers as $number){
    $phones[] = [
        'number' => $number
    ];
}

$home->phones()->createMany($phones);