应该如何热切加载属性? [英] How should attributes be eager loaded?

查看:69
本文介绍了应该如何热切加载属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型上有一组属性/访问者,它们在计算特定飞机类型的飞行次数.有没有一种方法只在我需要它们时才返回?如果将它们添加到appends[],则在加载所有资源时会出现N+1问题.

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();
        }

当我序列化此模型以发送给Vue时,我希望能够调用$aircraftType->load('total_flights'),就像我可以建立关系一样.我在这里想念什么吗?我尝试在实例上调用getAttributes方法,该方法获取值,但仅 值.我想像与人际关系一样简单地包含它.

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>

理想情况下,我正在寻找withAttributes方法.

Ideally, I'm looking for a withAttributes method.

推荐答案

如果遇到您的问题,我想这应该可以解决问题:

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

$aircraft_flights = $aircraft->total_flights;

假设$ aircraft是Aircraft的实例

Supposing $aircraft is an instance of Aircraft

这篇关于应该如何热切加载属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆