简体   繁体   中英

How to save update from relationships model Laravel 5.3

I want to save an update from One to Many relation model in Laravel 5.3, but I have this error.

FatalThrowableError in HasOneOrMany.php line 221: Type error: Argument 1 passed to Illuminate\\Database\\Eloquent\\Relations\\HasOneOrMany::save() must be an instance of Illuminate\\Database\\Eloquent\\Model, instance of Illuminate\\Database\\Eloquent\\Collection given, called in C:\\xampp\\htdocs\\wismasejahtera\\app\\Http\\Controllers\\JurnalController.php on line 129

Here is my Jurnals model:

public function djurnals()
{
    return $this->hasMany('App\DJurnals', 'jurnal_id');
}

And here is my Djurnals model:

public function jurnals()
{
  return $this->belongsTo('App\Jurnals');
}

public function rekenings()
{
  return $this->belongsTo('App\Rekenings');
}

And here is my Controller:

$jurnal = Jurnals::find($id);
  $jurnal->no_jurnal = $request->no_jurnal;
  $jurnal->tgl_jurnal = $tglJurnalFix;
  $jurnal->keterangan = $request->keterangan;
  $jurnal->save();

  //ini Array
  $kode_rekening = $request->kode_rekening;

  for($i=0; $i<count($kode_rekening); $i++){
    $djurnal = Djurnals::where('jurnal_id', $id)->get();
    $djurnal->kode_rekening = $request->kode_rekening[$i];
    $djurnal->keterangan_rekening = $request->keterangan_rekening[$i];
    $djurnal->d_k = $request->d_k[$i];
    $djurnal->jumlah = $request->jumlah[$i];

    if($request->d_k[$i] == 'D'){
      $saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
                                ->increment('saldo', $request->jumlah[$i]);
    }
    else{
      $saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
                                ->decrement('saldo', $request->jumlah[$i]);
    }
    $jurnal->djurnals()->save($djurnal);
  }
  return Redirect::to('jurnal');

And the error is in this row in Controller:

$jurnal->djurnals()->save($djurnal);

When I use this way to save a new jurnal and djurnal, it works correctly. But, When I try to save an update, it show an error. How can I save this update data to database? Anyone can help me?

Since you use the jurnal_id to get the Djurnals model, you need to save it directly.

Replace

Djurnals::where('jurnal_id', $id)->get();

With

Djurnals::where('jurnal_id', $id)->first();

Replace

$jurnal->djurnals()->save($djurnal);

With

$djurnal->save();

$jurnal->djurnals()->save($djurnal); Should be used only when saving a newly created model.

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