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

时间:2019-07-06 09:13:36

标签: php laravel relation

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

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

和在手机型号中:

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

现在在我的控制器中,当我插入Home时,我想使用它来向Phone表中添加与{{1相同的id }}。这是我现在插入的方式:

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); } 和许多Home

2 个答案:

答案 0 :(得分:1)

$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);

答案 1 :(得分:0)

自创建家庭以来,可以在关系上使用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