简体   繁体   中英

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

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 . 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.

$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

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 :

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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