R
R
Rooly2021-04-16 11:13:32
Laravel
Rooly, 2021-04-16 11:13:32

Lazy loading resource in Laravel if model method doesn't return relation?

Laravel has a nice $this->whenLoaded function for ApiResource for lazy loading of model relationships https://laravel.com/docs/8.x/eloquent-resources#co... .

I have such a problem that I have a property on the model that does not return a relation, but goes to another table in the database, collects apartments according to a certain condition and adds it all to an array (PhpMyAdmin designer below)

607946f1edad0909707317.png

In this case, I have addresses and the apartments in them are stored by users in a separate field (well, so as not to produce a lot of addresses, our team leader said that it’s right to do this and we do it, I’m Toko Junior and I’m still learning ¯\_(ツ)_/¯ )

The code for renting apartments is working and looks like this

Address.php

public function apartments() {
  return $this->clients->map(function ($item) {
      return $item->apartment;
  })->sort()->flatten();
}


I want to make AdressResource so that it is lazily loaded also through with (or somehow differently, so that the loading mechanism when calling Adresss:with('apartments')->get()) is something like this (but this naturally does not work ).

class Address extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            "id" => $this->id,
            "city" => $this->ctiy,
            "street" => $this->address,
            "house" => $this->house,
            $this->corpus ?? "corpus" => $this->corpus,
           ?? вот эта строчка нужно чтобы была ленивой, но я не могу придумать логику --> "apartments" => $this->apartments()
        ];
    }
}


PS A many-to-many connection is assumed that the office will serve many addresses, and here I'm thinking of making a one-to-many connection after all. Here, as it were, there are offices and one pack of addresses refers to one office, and the other pack to another (well, in short, like in the mail, like some addresses go there, and others go here).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Tokarev, 2021-04-22
@ZetIndex_Ram

apartments()describe through hasManyThrough . If the standard features are hasManyThroughnot enough, you can use the eloquent-has-many-deep package .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question