【发布时间】:2020-03-16 04:30:16
【问题描述】:
我的模型上有一组属性/访问器,用于计算特定飞机类型的航班数量。有没有办法只在我想要它们时返回它们?如果我将它们添加到appends[],我会在加载所有资源时遇到N+1 问题。
/**
* 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 方法,该方法获取值,但仅 获取值。我想简单地将它包含在关系中。
<total-flights :data-aircraft-type="{{ $aircraftType->getAttribute('total_flights') }}"></total-flights>
理想情况下,我正在寻找withAttributes 方法。
【问题讨论】:
-
显示你的 Vue 逻辑并且你想发送
$aircraftType对象对吗? -
为什么 Vue 逻辑很重要?是的,我正在尝试从 js 访问
aircraftType.total_flights。 -
为什么要为此使用访问器函数,而不是关系?
-
会更适合恋爱吗?我基本上是在尝试获取所有此类飞机的所有航班,这听起来像是多对多的关系。有没有办法在没有数据透视表的
AircraftType模型上定义它? -
@AlexGodbehere 我不知道你的确切数据结构,但像
public function flights() { return $this->hasMany('App\Flight', 'aircraft_type_id'); }这样的东西会让你做像AircraftType::withCount('flights')这样的事情。
标签: php laravel eager-loading