How should attributes be eager loaded?

馋奶兔 提交于 2020-01-05 05:27:21

问题


I have a set of attributes/accessors on my model that are working out the number of flights for a specific aircraft type. Is there a way to only return these when I want them? If I add them to appends[] I get an N+1 problem when loading all the resources.

        /**
         *    Gets the number of flights flown by the aircraft
         */
        public function getTotalFlightsAttribute () {

            return Flight::whereHas('aircraft', function($query) {

                $query->where('aircraft_type_id', '=', $this->id);
            })
                         ->count();
        }

I'd like to be able to call $aircraftType->load('total_flights') when I'm serializing this model to send to Vue to like I can with relationships. Am I missing something here? I've tried to call the getAttributes method on the instance, which gets the value, but only the value. I want to simply include it like I can with relationships.

<total-flights :data-aircraft-type="{{ $aircraftType->getAttribute('total_flights') }}"></total-flights>

Ideally, I'm looking for a withAttributes method.


回答1:


If I get your problem, I guess this should do the job :

$aircraft_flights = $aircraft->total_flights;

Supposing $aircraft is an instance of Aircraft




回答2:


If you have a relationship from Flight to Aircraft, you should have the inverse from Aircraft to Flight. With that relationship setup you can get the relationship count:

$aircrafts = Aircraft::withCount('flights')->......->get();

Then you can remove that accessor from appends as these Aircraft models retrieved will have a flights_count attribute.



来源:https://stackoverflow.com/questions/58954629/how-should-attributes-be-eager-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!