Php 如何解决与模型上的$appends属性冲突的Laravel select查询?

Php 如何解决与模型上的$appends属性冲突的Laravel select查询?,php,laravel,orm,eloquent,Php,Laravel,Orm,Eloquent,我有一种情况,我需要一个特定的属性访问器自动附加到我的一个模型中: class Mission extends Eloquent { protected $appends = ['launch_date_time']; public function getLaunchDateTimeAttribute() { return ($this->attributes['launch_approximate'] == null) ? $this->at

我有一种情况,我需要一个特定的属性访问器自动附加到我的一个模型中:

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\u date\u time
属性依赖于我的数据库中实际存在的模型的两个其他字段

但是,我现在想执行一个只返回一定数量字段的查询,因为这将通过AJAX发送多次,我希望使用尽可能少的资源:

// AJAX GET
// missions/all
public function all() {
    $allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image']);
    return Response::json($allMissions);
}
这里的问题是,我不再需要
launch\u date\u time
属性,因此我已将其排除,**这样做时,我的AJAX请求无法成功工作:

Undefined index: launch_approximate on line 78 of H:\myproj\app\models\Mission.php
这显然是因为我的模型试图附加
launch\u date\u time
,其中
launch\u approximate
是的依赖项。如果我包含所有必需的依赖项,则所有这些依赖项都会显示我要附加的任何“我的属性”:

$allMissions = Mission::with('featuredImage')->get(['mission_id', 'name', 'featured_image', 'launch_approximate', 'launch_exact', 'launch_date_time']);

这是不可取的。是否有一种解决方案可以保留这两种设置?

它不起作用的原因是您没有在查询中使用
get
方法从数据库检索所需字段。这就是为什么您无法访问
launch\u exact
launch\u approxical
,因为它们未在您的模型实例中设置

所以要让它像你想的那样工作。在访问它们之前,您必须检查是否设置了
launch\u exact
launch\u approximate

public function getLaunchDateTimeAttribute() {
    if(isset($this->attributes['launch_approximate']) && $this->attributes['launch_exact']) {
        return ($this->attributes['launch_approximate'] == null) ? $this->attributes['launch_exact'] : $this->attributes['launch_approximate'];
    } 

    return null;
}

您还可以在模型中设置带有
$visible
属性的白名单和带有
$hidden
属性的黑名单,以便在输出到json或数组时不显示某些属性查看文档:

谢谢mate帮助我!:)