afifridho
afifridho

Reputation: 13

Laravel insert data to one to one relation table

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

Upvotes: 1

Views: 3387

Answers (1)

Marcus
Marcus

Reputation: 1848

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

Upvotes: 1

Related Questions