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

时间:2015-06-18 10:30:51

标签: php laravel orm eloquent

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

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_timelaunch_approximate是其依赖关系。如果我包含所有必需的依赖项,那么我想要追加的所有属性都会出现:

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

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

1 个答案:

答案 0 :(得分:0)

它不起作用的原因是因为您没有在查询的var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs"); ref.orderByChild([the child node to compare to]).equalTo([what you are searching]).on("child_added", function(snapshot) { //do something with the data in snapshot }); 方法中从数据库中检索必需的字段。这就是您无法访问getlaunch_exact的原因,因为它们未在您的模型实例中设置。

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

launch_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的黑名单,以便在输出到json或数组时不显示某些属性,请查看文档:{ {3}}