简体   繁体   English

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

[英]How to insert a one to many relationship in Laravel

I have a one-to-many relationship in between the Home model and Phones model 我在“ Home模型和“ Phones模型之间存在一对多关系

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

and in Phone model: 在手机型号中:

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

Now in my controller, when I insert the Home , I want to use it to be able to add unlimited numbers to the Phone table with the same id of Home . 现在在控制器中,当我插入Home ,我想使用它来为idHomePhone表添加无限号码。 Here is how I insert now: 这是我现在插入的方式:

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

Now I want to know how can I insert Home with many Phones in phone table and realtionship. 现在,我想知道如何在电话表和房地产中插入带有许多Phones Home

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

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

Update with example: 更新示例:

suppose you are using multiple input fields to take numbers input. 假设您正在使用多个输入字段进行数字输入。

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

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

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

Since you have created your Home, you can use save or saveMany on the relation : 由于已经创建了主页,因此可以在关系上使用savesaveMany

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM