Ad

BelongsTo–hasOne Relationship Returns Null

- 1 answer

I'm trying to make a relationship in Laravel and when I use a hasOne relation it returns null.

The table format is like this:

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

Here's my code:

Model SocioGf:

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

Model socio:

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

Model grupoFamiliar:

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

In my grupoFamiliarController I return:

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

So in the gruposFamiliares.blade.php I try to access this way:

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

In the second line the dd shows a null variable, any idea why?

Ad

Answer

What you need is the relation belongsToMany

In model socio:

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

In model grupoFamiliar:

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

Then you can access socios and gruposFamiliares like this:

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

Each of these lines will return a collection of Socios and GruposFamiliares.

Ad
source: stackoverflow.com
Ad