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"
2
Answers
Try :
If you want to search using some keys inside the residentes relationship you can use whereHas
Also try to mention the local_key and the foreign_key in the relationship itself reference : https://laravel.com/docs/9.x/eloquent-relationships
Please try the following in the place of key give actual field names.