Home > Back-end >  Retrieving data from hasMany Relationship
Retrieving data from hasMany Relationship

Time:01-05

I want to show data from 'personas' (parent table) that has at least one 'residente' (child table), its a one to many relationship, and i want to show data of that residente too. I was trying to do it using the has() method like the laravel documentation says: https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence but it does not work.

Models looks like this

//in the Persona class

  public function residentes()
    {
        return $this->hasMany(Residente::class);
    }

//in the Residente class

public function persona()
  {
    return $this->belongsTo(Persona::class);
  }


//in the PersonasController

public function index()
    {
        $personas = Persona::has('residentes')->get();

        dd($personas);
           
    }

the Result enter image description here //it doesn't get the data from "residentes"

CodePudding user response:

Try :

 public function index()
{
    $personas = Persona::with('residentes')->get();
    dd($personas);
       
}

If you want to search using some keys inside the residentes relationship you can use whereHas

Persona::with('residentes')
       ->whereHas('residentes',function($residente){
           return $residente->where('column_name',$value);
         })->get();

Also try to mention the local_key and the foreign_key in the relationship itself reference : https://laravel.com/docs/9.x/eloquent-relationships

return $this->hasMany(Comment::class, 'foreign_key', 'local_key');

CodePudding user response:

Please try the following in the place of key give actual field names.

//in the Persona class
    
public function residentes()
{
   return $this->hasMany(Residente::class, 'foreign_key', 'local_key');
}
    
//in the Residente class
    
public function persona()
{
    return $this->belongsTo(Persona::class,'foreign_key', 'owner_key');
}
    
    
//in the PersonasController
    
public function index()
{
    $personas = Persona::with('residentes')->get();
    foreach($personas as $person){
       echo "<pre>";
       print_r($person->residentes()->get()->toArray());
     }
}
  • Related