1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Laravel model with relationship loads all records not only relationships

Discussão em 'Outras Linguagens' iniciado por Tamer, Outubro 3, 2024 às 20:22.

  1. Tamer

    Tamer Guest

    I have a model called MeterReading, and another called Client, where a client can have multiple meter readings.

    here are the relationships as defined:

    in Client

    public function readings()
    {
    return $this->hasMany(MeterReading::class)->orderByDesc('created_at');
    }


    and in MeterReading

    public function client()
    {
    return $this->belongsTo(Client::class)->withTrashed();
    }


    and both have the relationships defined in:

    protected $with


    now, when I load meter readings using queries, like this one:

    $readings= MeterReading::where('month', $this->month)
    ->where('year', $this->year)
    ->orderByDesc('meter_readings.created_at')->paginate($this->perPage);


    It loads all the 4000 records of clients, not only those related to the selected readings, and upon investigation, I found that it calls the clients as follows:

    select * from `clients` where `clients`.`id` in (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)


    the migrations are defined correctly, and both clients.id and client_id are matching types.

    Note that client ids are unique of course, and they are a formatted string, and cannot be null nor 0.

    why does this happen? any ideas to fix this?

    Continue reading...

Compartilhe esta Página