【发布时间】:2015-09-03 22:43:23
【问题描述】:
我有一种情况,我需要一个特定的属性访问器自动附加到我的模型之一:
class Mission extends Eloquent {
protected $appends = ['launch_date_time'];
public function getLaunchDateTimeAttribute() {
return ($this->attributes['launch_approximate'] == null) ? $this->attributes['launch_exact'] : $this->attributes['launch_approximate'];
}
}
如您所见,这个 launch_date_time 属性依赖于我的模型的其他两个字段,这些字段实际上在我的数据库中。
但是,我现在想执行一个只返回一定数量字段的查询,因为这将通过 AJAX 多次发送,我宁愿使用尽可能少的资源:
// AJAX GET
// missions/all
public function all() {
$allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image']);
return Response::json($allMissions);
}
这里的问题是我不再需要 launch_date_time 属性,所以我已经排除了它,**这样做,我的 AJAX 请求无法成功:
Undefined index: launch_approximate on line 78 of H:\myproj\app\models\Mission.php
这显然是因为我的模型试图附加launch_date_time,其中launch_approximate 是其依赖项。如果我包含所有必需的依赖项,那么所有我想要附加的属性都会出现:
$allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image', 'launch_approximate', 'launch_exact', 'launch_date_time']);
这是不可取的。有没有可以保留两种设置的解决方案?
【问题讨论】: