Insert in 2 different laravel tables?

1

I want to make an insert in 2 different tables of the database. I have the holiday table that stores the holidays and I have a calendar, in which calendar events must be saved to show it every time a vacation is approved, then I have:

Controller method: In which I keep on vacation if the holidays are approved or not, and I try to call the other model, to insert events in the calendar table.

$vacation=new Vacation();
    $id = $request->get('id');
    $vacation = Vacation::find($request['id']);
    $vacation-> aceptado = '1';
    $vacation->save();

    $evento = new CalendarioEvento;
    $evento -> fechaIni = $vacation['date_from'];
    $evento -> fechaFin = $vacation['date_to'];
    $evento -> todoeldia = true;
    $evento -> color = 'rgb(244, 67, 54)';
    $evento -> titulo = $vacation['type'];
    $vacation-> evento()->save($evento);

    return redirect('/vacation/request');

Model:

class CalendarioEvento extends Model{
   public function vacation(){
      $this->belongsTo('App\Vacation');
   }
}


class Vacation extends Model{
   public function evento()
   {
      return $this->hasMany('App\CalendarioEvento');
   }
}

and the error it gives me is:

    QueryException in Connection.php line 729:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'vacation_id' in 'field list' (SQL: insert into 'calendario_eventos' ('fechaIni', 'fechaFin', 'todoeldia', 'color', 'titulo', 'vacation_id', 'updated_at', 'created_at') values (, , 1, rgb(244, 67, 54), , 2, 2018-02-20 11:58:06, 2018-02-20 11:58:06))

With which I understand that when I add the part of the method that adds the calendar events it looks for the id of vacations (that do not have to look for), in the table that does not have to look for, how can I solve this for do the insert in the second table after doing the first update ?

    
asked by Peisou 20.02.2018 в 13:02
source

1 answer

1

If you do not need a relationship between the tables (as you explain in the comments), you can simply use the save() method in each of them (separately) or you can use firstOrCreate() or updateOrCreate() or create() for the new model.

// Las tres primeras líneas no son necesarias, se pueden reemplazar con Route Model Binding

$vacation=new Vacation();
$id = $request->get('id');
$vacation = Vacation::find($request['id']);

$vacation-> aceptado = '1';
$vacation->save();

$evento = new CalendarioEvento;
$evento -> fechaIni = $vacation['date_from'];
$evento -> fechaFin = $vacation['date_to'];
$evento -> todoeldia = true;
$evento -> color = 'rgb(244, 67, 54)';
$evento -> titulo = $vacation['type'];
$vacation->save();

or with the method create() for CalendarEvent, passing an array with the values of the fields:

$evento = CalendarioEvento::create([
    'fechaIni' => $vacation['date_from'],
    'fechaFin' => $vacation['date_to'],
    ....
]);
    
answered by 20.02.2018 / 15:34
source