1

How can I insert data (that linking each other) to the table 'PEMBATALAN' that has one to one relation (have foreign key in both table) to the other table 'PERMINTAAN'.

here is the 'pembatalan' model code:

class Pembatalan extends Model
{
    public $table = "PEMBATALAN";
    public $primaryKey = "ID_PEMBATALAN";
    public $fillable = array(
        'PERMINTAAN_ID',
        'ALASAN_PEMBATALAN',
        'TGL_PEMBATALAN',
        'FILE_PEMBATALAN',
        'STATUS_PEMBATALAN',
    );
    public function permintaan() {
        return $this->belongsTo('Permintaan', 'PERMINTAAN_ID', 'ID_PERMINTAAN');
    }
}

'Permintaan' model code:

class Permintaan extends Model
{

    public $table = "PERMINTAAN";
    public $fillable = array(
        'NOMOR_TICKET',
        'TGL_PERMINTAAN',
        'NAMA_REQUESTER',
        'PEMBATALAN_ID',
    );
    public $primaryKey = "ID_PERMINTAAN";

    public function tikpro() {
        return $this->belongsToMany('Tikpro','TIKPRO_ID','ID_TIKPRO');
    }
    public function pembatalan() {
        return $this->hasOne('Pembatalan','PEMBATALAN_ID','ID_PEMBATALAN');
    }
}

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
afifridho
  • 13
  • 1
  • 3

1 Answers1

1

Create your Permintaan and then use that reference to create the relation

Only Pembatalan needs a foreign key of Permintaan or the other way around.

$p = Permintaan::create([
     'NOMOR_TICKET' =>$value,
     'TGL_PERMINTAAN' =>$value,
     'NAMA_REQUESTER' =>$value,
 ]);

$p->pembatalan()->create([
    'ALASAN_PEMBATALAN' =>$value,
    'TGL_PEMBATALAN' =>$value,
    'FILE_PEMBATALAN' =>$value,
    'STATUS_PEMBATALAN' =>$value,
 ]);

Laravel docs has a very good explanation on one to one relationships using hasOne and belongs to

Marcus
  • 1,850
  • 1
  • 12
  • 24