简体   繁体   中英

Lazy loading resource in Laravel, if the method in the model does not return a relation?

Could you help, me dear colleagues

In Laravel for ApiResource, there is a great function $this->whenLoaded for lazy loading of model relationships https://laravel.com/docs/8.x/eloquent-resources#conditional-relationships .

I have such a problem that I have a property in the model that does not return a relation, but goes to another table in the database, collects apartments by a certain condition, and puts it all in an array (phpMyAdmin designer at the bottom)

https://imgur.com/a/mbY2ynG

In this case, I have addresses and apartments in them are stored by users in a separate field (well, in order not to produce too many addresses, we have Team Lead said that this is the right thing to do and we do it, I am a Junior and still learning \ (ツ) /)

The code for taking apartments is working and looks like this

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

I want to make the AdressResource so that it is also lazily loaded via with (or something else, so that the loading mechanism when accessing 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,
           ?? this line needs to be lazy, but I can't think of any logic. --> "apartments" => $this->apartments()
        ];
    }
}

PS relationship many to many it is assumed that the office will serve many addresses and here I think to make a connection after all one to many. Here, as if there are offices and one pack of addresses refers to one office, and another pack to another (well, in short, as in the mail, like some addresses there, and others here)

You should be able to rewrite the logic to a relationship and i guess that will solve your problem, so you can use ordinary whenLoaded() calls.

public function apartments() {
    return $this->belongsToMany(Apartment::class, 'clients', 'apartment_id', 'client_id');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM