Laravel 嵌套关系 returns null

Laravel Nesting relationship returns null

我有下一个数据库结构:

我的 Eloquent 模型中有下一个代码:

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');
}

我尝试在 where 子句中使用点来获取带有他的标签、polfzms 和基因的样本数据 - polfzms.gene

public function show($id)
{
    return Sample::with('labels', 'polfzms.gene')->findOrFail($id);
}

但是我有一个"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
      }
   ]
}

我使用最新的 laravel 版本。我该如何解决?

您的 Gene 关系得到 null,因为您没有明确定义外键,也没有遵循 Eloquent 命名约定。

Eloquent 期望外键为 gene_id,而您的模式具有外键 id_gene.

要解决此问题,请更改您的架构以将外键定义为 gene_id,或者按如下方式更新您的关系:

public function gene()
{
    return $this->belongsTo('App\Gene', 'id_gene');
}