Reputation: 653
I have next db structure:
And I have next code in my Eloquent models:
Sample.php
public function polfzms()
{
return $this->belongsToMany('App\Polfzm');
}
Polfzm.php
public function samples()
{
return $this->belongsToMany('App\Sample');
}
public function gene()
{
return $this->belongsTo('App\Gene');
}
Gene.php
public function polfzms()
{
return $this->hasMany('App\Polfzm');
}
I try to get sample data with his labels, polfzms and gene using dot in where clause - polfzms.gene
public function show($id)
{
return Sample::with('labels', 'polfzms.gene')->findOrFail($id);
}
But I have got a "gene":null
{
"id":18,
"person_id":1,
"prefix_id":3,
"labels":[
{
"id":1,
"name":"Name1",
"meaning":"dfdf",
"pivot":{
"sample_id":18,
"label_id":1
}
},
],
"polfzms":[
{
"id":1,
"name":"G20210",
"id_gene":1,
"pivot":{
"sample_id":18,
"polfzm_id":1
},
"gene":null
}
]
}
I use latest laravel version. How can I fix it?
Upvotes: 0
Views: 709
Reputation: 17388
You're getting null
for your Gene
relation, because you have not explicitly defined a foreign key, nor followed the Eloquent naming convention.
Eloquent expects the foreign key to be gene_id
, whereas your schema has the foreign key id_gene
.
To fix this, either change your schema to define the foreign key as gene_id
, or update your relationship as follows:
public function gene()
{
return $this->belongsTo('App\Gene', 'id_gene');
}
Upvotes: 1