Hello everyone!
I'm having an issue trying to load a relationship in Laravel using Eloquent, and I was wondering if anyone could help me solve it.
I'm working on a project where I have two models: UaderArea and UaderLugares, and I'm trying to establish a relationship between them. Each UaderArea belongs to one UaderLugares, and the relationship is defined like this in the UaderArea model:
public function lugares()
{
return $this->belongsTo(UaderLugares::class, 'lugar', 'cod_lugar');
}
When I execute:
$resultados = UaderArea::with('lugares')
->get();
It returns a JSON like this:
{
"id_area": 23,
"area": "PRIVADA",
"id_secretaria": 3,
"lugar": 0,
"id_area_dj": null,
"lugares": {
"cod_lugar": 0,
"lugar": "RECTORADO",
"foto": null,
"uacad": 0,
"cod_lugar_dj": 0
}
}
That's fine, but if I replace the query like this:
$resultados = UaderArea::with('lugares:lugar')
->get();
It returns:
{
"id_area": 23,
"area": "PRIVADA",
"id_secretaria": 3,
"lugar": 0,
"id_area_dj": null,
"lugares": null
}
My problem is that I need the fields "id_area", 'area', and from the table uader_lugares (model UaderLugares), the field 'lugar'.
Hi @valeno12
You need to also specifiy the key from the relationship table so that the join operation that is performed by the Eloquent internally fetches the correct data.
Here is the revised code
$resultados = UaderArea::with('lugares:lugar,cod_lugar')
->get();
I hope this resolves your issue. Thanks
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community