I want to join two tables with laravel relationship, but I’ve gotten stuck.
I have 2 MySSL tables
table strans
+ id
+ trans_code
+ trans_description
table step
+ step_id
+ step_trans_code
+ step_proc_sequence
My models look like this:
class Strans extends Model
{
protected $table = 'hc_strans';
protected $fillable = [
'trans_code', 'trans_description', 'trans_sk_code'
];
public function step()
{
return $this->hasMany(Sstep::class, 'step_trans_code', 'trans_code');
}
}
class Sstep extends Model
{
protected $table = 'hc_sstep';
protected $fillable = [
'step_trans_code', 'step_proc_sequence'
];
public function transCode()
{
return $this->belongsTo(Strans::class, 'trans_code', 'step_trans_code');
}
}
At the step controller, I called the relationship:
$step = Sstep::with('transCode')->get();
The table data have all the relationship values. But when I try the relationship, transCode variable returns a null value.
I tried with manual query, it’s no problem.
"data": [
{
"step_id": 8,
"step_trans_code": "MUT",
"step_proc_sequence": 80,
"trans_code": null
}
]
Am I doing it wrong in the relationship?
2
Answers
Laravel has a naming convention, for example in belongs to the relationship it will consider the foreign key as stran_id, so define the foreign key explicitly.