Home > Enterprise >  Laravel 8: how to retrieve data of a one to one relationship in existing database?
Laravel 8: how to retrieve data of a one to one relationship in existing database?

Time:10-05

I am having some problems retrieving data in a one-to-one relationship. I have this existing Table and I want to retrieve the data from rfp_details. here is my code

//rfpmain model
protected $table = 'accounting.request_for_payment';
public function rfpDetail(){
    return $this->hasOne(RfpDetail::class);
}


//rfp detail model
protected $table = 'accounting.rfp_details';
public function rfpMain(){
    return $this->belongsTo(RfpMain::class);
}

//rfp controller
public function show($id)
{
    $rfpMain = RfpMain::findOrFail($id);
    $rd = $rfpMain->rfpDetails;
    dd($rd);
}

below is the structure of my existing database

enter image description here

CodePudding user response:

you need to define the foreign key in your relationship because if you can't define it then it will take the default value which is different in your case.

You need to replace from

public function rfpDetail(){
    return $this->hasOne(RfpDetail::class);
}

To

public function rfpDetail(){
    return $this->hasOne(RfpDetail::class,'rfpid');
}
  • Related