#Issue loading relationship in Eloquent: lugares:null

12 messages · Page 1 of 1 (latest)

wanton quail
#

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'.

nova mantle
#
$books = Book::with('author:id,name,book_id')->get();
#
return $this->belongsTo(UaderLugares::class, 'lugar', 'cod_lugar');

That is not correct. lugar is a text field and the second parameter is supposed to be an id.

People should stop fighting the framework

#

UaderLugares
UaderArea
One model is singular and the other plural. It's not even consistent.

wanton quail
wanton quail
#

When this database was created, no standard was followed. Everything was done haphazardly and poorly.

nova mantle
#

been there

#

I'm not seeing cod_lugar in the first json dump

#

did you try preserving the ids as shown in the docs screenshot?