Update data into table from dynamically created input field

心已入冬 提交于 2019-12-02 05:00:48

问题


I have 2 models Tour.php

public function Itinerary()
{
    return $this->hasMany('App\Itinerary', 'tour_id');
}

and

Itinerary.php

public function tour() 
{
    return $this->belongsTo('App\Tour', 'tour_id');
}

tours table:

id|title|content

itineraries table:

id|tour_id|day|itinerary

I have used vue js to create or add and remove input field for day and plan dynamically. And used the following code in tour.store method to insert into itineraries table:

    $count = count($request->input('day'));
$temp_day        = $request->input('day');
$temp_itinerary  =   $request->input('itinerary');

for($i = 0; $i < $count; ++$i) 
{

    $itinerary = new Itinerary;
    $itinerary->tour_id        =  $tour->id;
    $itinerary->plan      =   $temp_itinerary[$i];        
    $itinerary->day            =   $temp_day[$i];
    $itinerary->save();
}

And was successful in inserting the records.And applied same code in tour.store method. Instead of updating the rows, it inserted new rows to the table. What would be the best solution for this ?


回答1:


For updation try this code

$itinerary = Itinerary::find($tour_id);
$itinerary->plan = $temp_itinerary[$i];        
$itinerary->day = $temp_day[$i];
$itinerary->save();



回答2:


The way you are using is to insert/create new records. To update you can use.

Itinerary::find($tour_id)->update(
   ['column_name'=> value]
);

Where find method takes a primary key of the table.

This will update your existing record. You can update as many columns as you want just pass in array update takes. You can also use save method as mentioned in other answer.

Check Laravel Update Eloquent

EDIT

$iterneary = Itenerary::where('tour_id', $tour_id)->first();

Now you can update this iterneary object to whatever you want.




回答3:


this is how i did it. First saved all the tours in $tours[] array.

foreach($tours as $tour) {
        $itinerary->tour()->updateOrCreate(['id'=> $tour['id']],$tour);
    }

updateOrCreate because you may need to add new tours while updating. I know this doesnt answer your issue exactly but this could atleast give you an idea.



来源:https://stackoverflow.com/questions/44540484/update-data-into-table-from-dynamically-created-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!