【问题标题】:belongsTo–hasOne relationship returns nullbelongsTo–hasOne 关系返回 null
【发布时间】:2020-05-16 05:49:10
【问题描述】:

我正在尝试在 Laravel 中建立关系,当我使用 hasOne 关系时,它返回 null。

表格格式是这样的:

┌─────────┐   ┌─────────────────┐   ┌───────────────┐
│ socio   │ ← │ socioGf         │ → │ grupoFamiliar │
├─────────┤   ├─────────────────┤   ├───────────────┤
│ id      │   │ idSocio         │   │ id            │
│         │   │ idGrupoFamiliar │   │               │
└─────────┘   └─────────────────┘   └───────────────┘

这是我的代码:

型号SocioGf

...
public function grupoFamiliar(){
     return $this->hasOne('App\GrupoFamiliar','id','idGrupoFamiliar')
     ->toSql();
}
public function socio(){
     return $this->hasOne('App\Socio','id','idSocio');
}
...

型号socio

...
public function socioGf(){
        return $this->belongsTo('App\SocioGf', 'idSocio', 'id');
}  
...

型号grupoFamiliar

...
public function socioGf(){
        return $this->belongsTo('App\SocioGf', 'idGrupoFamiliar','id');
} 
...

在我的grupoFamiliarController 我返回:

$gruposFamiliares = GrupoFamiliar::paginate($this->paginateNumber);        
return view('gruposFamiliares',compact('gruposFamiliares'));

所以在gruposFamiliares.blade.php我尝试这样访问:

@forelse($gruposFamiliares as $grupoFamiliar)
    {{dd($grupoFamiliar->socioGf)}}
    @foreach($grupoFamiliar->socioGf() as $gf)
        {{dd($gf->socio)}}
    @endforeach
@endforelse

在第二行中,dd 显示了一个空变量,知道为什么吗?

【问题讨论】:

  • 在hasOne关系中,“属于”的模型是必须保留外键的模型。看来你已经投资了

标签: php laravel eloquent laravel-blade


【解决方案1】:

你需要的是关系belongsToMany

在模型socio

...
public function gruposFamiliares(){
    return $this->belongsToMany(GrupoFamiliar::class, 'socioGf_table', 'socioId', 'grupoFamiliarId');
}
...

在模型grupoFamiliar

...
public function socios(){
    return $this->belongsToMany(Socio::class, 'socioGf_table', 'grupoFamiliarId', 'socioId');
}
...

然后你可以像这样访问sociosgruposFamiliares

$socio->gruposFamiliares()->get();
$grupoFamiliar->socios()->get();

这些行中的每一行都将返回一个 Socios 和 GruposFamiliares 的集合。

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2016-01-13
    • 2013-10-05
    相关资源
    最近更新 更多