[英]Laravel Nesting relationship returns null
I have next db structure: 我有下一个数据库结构:
And I have next code in my Eloquent models: 我的口才模型中还有下一个代码:
Sample.php Sample.php
public function polfzms()
{
return $this->belongsToMany('App\Polfzm');
}
Polfzm.php Polfzm.php
public function samples()
{
return $this->belongsToMany('App\Sample');
}
public function gene()
{
return $this->belongsTo('App\Gene');
}
Gene.php 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
我尝试在where子句中使用点获取带有他的标签,polfzms和基因的样本数据
polfzms.gene
public function show($id)
{
return Sample::with('labels', 'polfzms.gene')->findOrFail($id);
}
But I have got a "gene":null
但是我有一个
"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. 我使用最新的laravel版本。 How can I fix it?
我该如何解决?
You're getting null
for your Gene
relation, because you have not explicitly defined a foreign key, nor followed the Eloquent naming convention. 由于没有显式定义外键,也没有遵循Eloquent命名约定,因此您的
Gene
关系将得到null
。
Eloquent expects the foreign key to be gene_id
, whereas your schema has the foreign key id_gene
. gene_id
期望外键为gene_id
,而您的架构具有外键id_gene
。
To fix this, either change your schema to define the foreign key as gene_id
, or update your relationship as follows: 要解决此问题,请更改架构以将外键定义为
gene_id
,或按如下所示更新关系:
public function gene()
{
return $this->belongsTo('App\Gene', 'id_gene');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.